0% found this document useful (0 votes)
35 views77 pages

Unit III

Uploaded by

kaviya260703
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views77 pages

Unit III

Uploaded by

kaviya260703
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

UNIT III

CONTROL FLOW, FUNCTIONS


Conditionals: Boolean values and operators, conditional (if),
alternative (if-else), chained conditional (if elif-else); Iteration: state,
while, for, break, continue, pass; Fruitful functions: return values,
parameters, local and global scope, function composition, recursion;
Strings: string slices, immutability, string functions and methods,
string module; Lists as arrays. Illustrative programs: square root, gcd,
exponentiation, sum an array of numbers, linear search, binary search.
CONDITIONALS
• Flow of execution of instruction can be controlled using conditional
statements. Conditional statements have some Boolean expression.
Boolean expression can have relational operators or logical operators
or both.
Boolean Expressions
A boolean expression is an expression it‘s result is either true or false.
The following examples use the operator ==, which compares two
operands and produces True if they are equal and False otherwise:
>>> 9 == 9 >>>type(True)
True <class ‘bool’>
>>> 9 == 6 >>>type(False)
False <class ‘bool’>
Boolean expression can have relational operators or logical operators.
The == operator is one of the relational operators; the others are:
x==y #x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
Logical Operators
There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is similar to their meaning in English.

x> 0 and x < 10 is true only if x is greater than 0 and less than 10.

n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true,


not operator negates a boolean expression, so
Note:- Any nonzero number is interpreted as True

>>>95 and True >>>mark=95 >>>mark=102


True >>>mark>0 and mark<=100 >>>mark>0 and mark<=100
True False
SELECTION
Selection or Conditional statements give us the ability to check
conditions and change the behaviour of the program accordingly. The
syntax for if statement:
In python selection can be achieved through
if statement
elif Statement
if...elif...else
Nested if statements
Conditional statement (if)
General Syntax of if statement is
if <test_expression>:
<statements>

Here, the program evaluates the TEST EXPRESSION and will execute
statement(s) only if the text expression is True. If the text expression is
False, the statement(s) is not executed.
Example:
mark = 102
if mark >= 100:
The boolean expression after the if
print(mark, " is not a valid mark.")
statement is called the condition. If
print("This is always printed.")
it is true, then all the indented
Output
statements get executed.
102 is a not a valid mark.
This is always printed.
Alternative execution (if… else)
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax looks like
this:
if TEST EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Example
age=20
if age >= 18:
print("Eligible to vote")
else:
print("Not Eligible to vote")
Output:
Eligible to vote
Chained Conditionals
Sometimes there are more than two possibilities and we need more than two branches. The
syntax looks like this:
if TEST EXPRESSION1:
STATEMENTS_A
elif TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C

Each condition is checked in order. If the first is false, the


next is checked, and so on. If one of them is true, the
corresponding branch executes, and the statement ends.
Even if more than one condition is true, only the first true
branch executes.
Example
time=17
if time<12:
print(“Good Morning”)
elif time<15:
print(“Good Afternoon”)
elif time<20:
print(“Good Evening”)
else:
print(“Good Night”)
Output:
Good Evening
Nested conditionals
One conditional can also be nested within another. Indentation is the only way to
figure out the level of nesting. General Syntax of Nested if..else statement is

if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E
print(a);
Logical operators often provide a way to simplify nested conditional
statements. Example: Greatest of three numbers with
nested if
a=10 a=10
b=20 b=20
c=5 c=5
if a>b and a>c: if a>b:
print("Greatest number is ",a) if a>c:
elif b>a and b>c: print("Greatest number is ",a)
print("Greatest number is ",b) else:
else: print("Greatest number is ",c)
print("Greatest number is ",c) else:
if b>c:
print("Greatest number is ",b)
else:
print("Greatest number is ",c)
Output:
Greatest number is 20
Example: check if the number is Example: check if the number is positive
positive or negative or zero or negative or zero with nested if

num = float(input("Enter a number: ")) num = float(input("Enter a number: "))


if num == 0: if num >= 0:
print("Zero") if num == 0:
elif num>0: print("Zero")
print("Positive number") else:
else: print("Positive number")
print("Negative number") else:
print("Negative number")
ITERATION
Repeated execution of a set of statements is called iteration. Python has two
statements for iteration
 while statement
 for statement
The while statement
The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true. The general syntax for the while statement :

while TEST_EXPRESSION:
STATEMENTS

In while loop, test expression is checked first. The body of


the loop is entered only if the TEST_EXPRESSION
evaluates to True. After one iteration, the test expression is
checked again. This process continues until the
TEST_EXPRESSION evaluates to False.
n=5
Example: Python program to find sum of first n
numbers using while loop
sum=0
i=1
n=5
1<=5, sum=0+1=1
sum = 0
i=1+1=2
i=1
2<=5, sum=1+2=3
while i <= n: i=2+1=3
sum=sum+i 3<=5, sum=3+3=6
i=i+1 i=3+1=4
print(“The sum is”, sum) 4<=5, sum=6+4=10
Output i=4+1=5
5<=5, sum=10+5=15
The sum is 210
i=5+1=6
6<=5
The for Statement
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. The general syntax for

for LOOP_VARIABLE in SEQUENCE:


STATEMENTS

Here, LOOP_VARIABLE is the variable that takes the


value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the
sequence. The body of for loop is separated from the rest
of the code using indentation.
Example Example:
marks = [95,98,89,93,86] sum=0
for i in range(5):
total = 0
sum=sum+i
for subject_mark in marks: print("Sum is ", sum)
total = total+subject_mark Output:
print("Total Mark is ", total) Sum is 10
Output: i=0, 0<5,sum=0+0=0
i=1,1<5, sum=0+1=1
Total Mark is 461
i=2,2<5, sum=1+2=3
i=3,3<5, sum=3+3=6
i=4,4<5, sum=6+4=10
i=5, 5<5
for i in range(1,10,1): for i in range(-2,-5,-1):
print(i) print(i)
-2,-3,-4 for i in range(1,10,-1):
1,2,3,4,5,6,7,8,9 i=-2,-2>-5 print(i)
i=-3,-3>-5 
i=-4,-4>-5 i=1, 1>10
for i in range(1,10,2): i=-5,-5>-5
print(i)
1,3,5,7,9 for i in range(-5,-2,1):
print(i)
for i in range(5): -5,-4,-3
print(i) i=-5,-5<-2,
i=-4,-4<-2
0,1,2,3,4
i=-3,-3<-2
for i in range(1,5): i=-2,-2<-2
print(i)
1,2,3,4
Break, Continue, Pass
You might face a situation in which you need to exit a loop completely
when an external condition is triggered.
There may also be a situation when you want to skip a part of the loop
and start next execution. Python provides break and continue statements
to handle such situations and to have good control on your loop.
• Break
• Continue
• Pass
Break
Example
The break statement in Python terminates the var = 10
current loop and resumes execution at the while var> 0:
next statement. The break statement can be print('Current variable value :', var)
used in both while and for loops. var = var -1
if var == 5:
Example
break
for letter in 'Welcome':
print "End!"
if letter == ‘c':
Output:
break
Current variable value : 10
print('Current Letter :', letter)
Current variable value : 9
Output:
Current variable value : 8
Current Letter : W
Current variable value : 7
Current Letter : e
Current variable value : 6
Current Letter : l
End!
The continue Statement:
The continue statement in Python returns the control to the beginning of the
while loop. The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
Example
Example
var = 10
for letter in 'Welcome':
while var> 0:
if letter == 'c':
print('Current variable value :', var)
continue
var = var -1
print('Current Letter :', letter)
if var == 5:
Output:
Current Letter : W continue
Current Letter : e print("End!“)
Current Letter : l Output:
Current Letter : o Current variable value : 10
Current variable value : 9
Current Letter : m
Current variable value : 8
Current Letter : e Current variable value : 7
Current variable value : 6
Current variable value : 5
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
End!
The else Statement Used with Loops
The else Statement Used with Loops Python supports to have an else statement
associated with a loop statements.
 If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
 If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
while loop with else
We can have an optional else block with while loop as well. The else part is
executed if the condition in the while loop evaluates to False. The while loop
can be terminated with a break statement. In such case, the else part is ignored.
Hence, a while loop's else part runs if no break occurs and the condition is false.
counter = 0
while counter < 3:
print("Inside loop") Here, we use a counter variable to print the
counter = counter + 1 string Inside loop three times. On the forth
else: iteration, the condition in while becomes False.
print("Inside else") Hence, the else part is executed.
Output
Inside loop
Inside loop
Inside loop
Inside else
for loop with else
A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts. break statement can be used
to stop a for loop. In such case, the else part is ignored. Hence, a for loop's else
part runs if no break occurs.
Example
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output: Here, the for loop prints items of the list until the
0 loop exhausts. When the for loop exhausts, it
1 executes the block of code in the else and prints
5
No items left.
The pass Statement
• In Python programming, pass is a null statement. The difference between a comment
and pass statement in Python is that, while the interpreter ignores a comment entirely,
pass is not ignored. However, nothing happens when pass is executed. It results into
no operation (NOP).
• Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.

Example Example
sequence = {'p', 'a', 's', 's'} def function(args):
for val in sequence: pass
pass
Sum of n numbers Sum of n numbers using for loop:
using while loop: n=int(input("enter n"))
n=int(input(“Enter n")) sum=0
i=1
for i in range(1,n+1,1):
sum=0
while(i<=n): sum=sum+i
sum=sum+i print(sum)
i=i+1
print(sum)

output
Enter n
10
55
Factorial of a numbers: n=5
n=int(input(“Enter n:")) i=1
i=1
fact=1 fact=1
while(i<=n): 1<=5, fact=1*1=1, i=1+1=2
fact=fact*i 2<=5, fact=1*2=2, i=2+1=3
i=i+1
print(fact)
3<=5, fact=2*3=6, i=3+1=4
4<=5, fact=6*4=24, i=4+1=5
output 5<=5, fact= 24*5=120, i=5+1=6
Enter n: 5 6<=5
120
Sum of digits of a number:
n=123
n=int(input(“Enter a number"))
sum=0
sum=0
123>0
while(n>0):
a=123%10=3, sum=0+3=3,n=123//10=12
a=n%10
12>0
sum=sum+a
a=12%10=2, sum=3+2=5, n=12//10=1
n=n//10
1>0
print(sum)
a=1%10=1, sum=5+1=6, n=1//10=0
0>0
Output
Enter a number
123=1+2+3=6
6
Reverse the given number:
n=int(input(“Enter a number"))
sum=0+3=3
sum=0
while(n>0): sum=3*10+2=32
a=n%10 sum=32*10+1=321
sum=sum*10+a
n=n//10
print(sum)

Output
Enter a number
123
321
Palindrome or not Palindrome or not
n=int(input(“Enter a number")) n=int(input(“Enter a number"))
org=n x=str(n)
sum=0 org=n
while(n>0): sum=0
a=n%10 for i in range(len(x)):
sum=sum*10+a a=n%10
n=n//10 sum=sum*10+a
if(sum==org): n=n//10
print("The given no is palindrome") if(sum==org):
else: print("The given no is palindrome")
print("The given no is not palindrome") else:
Output print("The given no is not palindrome")
Enter a number121 Output
The given no is palindrome Enter a number121
The given no is palindrome
Armstrong number or not (only for 3 digits)
n=int(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a**3
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
output
enter a number 153 (13 +53+33 )=153
The given number is Armstrong number
Armstrong number or not(any digit)
n=int(input(“Enter a number"))
x=str(n)
y=len(x)
org=n
sum=0
while(n>0):
a=n%10
sum=sum+pow(a,y)
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not Armstrong number")
Output
enter a number 54748=55 +45 + 75 +45 +85
The given number is Armstrong number
Program to print fibonacci series.
a=0
Output
b=1
Enter the number of terms: 5
n=int(input("Enter the number of terms: "))
Fibonacci Series:
print("Fibonacci Series: ")
0
print(a,b)
1
for i in range(1,n-1,1):
1
c=a+b
2
print(c)
3
a=b
b=c
Program to check whether the number is a prime number or not
n=int(input("Enter the value of n"))
for i in range(2,n//2+1):
if(n%i==0):
print(“Not Prime”)
break
else:
print("Prime")
Output
Enter the value of n 151
Prime
Fruitful Function
• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
OUTPUT:
30
Void Function
A function that perform action but don’t return any value.
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Output:
30
Return values:

return keyword is used to return the values from the function.

example:
return( a) – return 1 variable
return (a,b ) – return 2 variables
return (a,b,c ) – return 3 variables
return (a+b) – return expression
return (8) – return value
Calculate area of circle using function:
def cal(r1):
return 3.14*r1*r1
r=int(input("enter r"))
print(cal(r))

OUTPUT:
enter r: 2
ans=
12.56
Find arithmetic operation of given number using function
def cal(a,b):
c=a+b
d=a*b
e=a-b
f=a//b
return (c,d,e,f)
a=int(input("enter a value :"))
b=int(input("enter b value : "))
print("addition , subraction, multiplicaion, division”)
print(cal(a,b))
Output
enter a value :34
enter b value : 23
addition ,subraction,multiplicaion,division of given values= (57, 782, 11, 1)
PARAMETERS / ARGUMENTS:

 Parameters are the variables which used in the function definition.


 Parameters are inputs to functions.
 Parameter receives the input from the function call.
 It is possible to define more than one parameter in the function definition.

Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with number of
arguments in the function call.

Example:
def student( name, roll ):
print("STUDENT NAME IS ",name)
print("STUDENT ROLL NO IS",roll)
student("George",98)

OUTPUT:
STUDENT NAME IS George
STUDENT ROLL NO IS 98
Keyword Parameters:
Python interpreter is able to use the keywords provided to match the values
with parameters even though if they are arranged in out of order.
Example:
def my_details(name,age):
print(“Name:”, name)
print(“Age:”, age)
return
my_details(age=56,name=“George)
Output
Name: George
Age: 56
Default parameter:
Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.

Example :
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")

OUTPUT:
Hello Kate, Good morning!
Hello Bruce, How do you do?
Variable length parameter
• Sometimes, we do not know in advance the number of arguments that will be
passed into a function.
• Python allows us to handle this kind of situation through function calls with
number of arguments.
• In the function definition we use an asterisk (*) before the parameter name to
denote this is variable length of parameter.
Example:
def student(*mark):
print("STUDENT NAME ,STUDENT RGNO, TOTAL, PERCENTAGE:",
mark)
student ("bala",102,450,90)

Output:
STUDENT NAME ,STUDENT REGNO,TOTAL,PERCENTAGE: ('bala', 102, 450, 90)
Local and Global Scope
Global Scope
• The scope of a variable refers to the places that you can see or access a
variable.
• A variable with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the function
Local Scope :
A variable with local scope can be used only within the function
def add():
b=20 Output
print(b) 20
c=a+b 70
print(c) 20
def sub(): 50
b=30 error
c=a-b
print(c)
a=50
add()
sub()
print(a)
print(b)
Function Composition:
• Function Composition is the ability to call one function from within
another function
• It is a way of combining functions such that the result of each function is
passed as the argument of the next function.
• In other words the output of one function is given as the input of another
function is known as function composition.
# Function to add 2 to a number
def add(x):
add(5)
return x + 2 Function call return 7
multiply(add(5)) multiply(7)
# Function to multiply 2 to a number return 14
def multiply(x):
return x * 2

# Printing the result of composition of add and multiply to add 2 to a number and then
multiply by 2
print("Adding 2 to 5 and multiplying the result with 2: ", multiply(add(5)))

Output:
Adding 2 to 5 and multiplying the result with 2: 14
Recursion
A function calling itself till it reaches the base
value - stop point of function call. Example: 5
factorial of a given number using recursion
Factorial of n fact(5)
def fact(n): 5*fact(4)
if(n==1 or n==0): 5*4*fact(3)
return 1
else:
5*4*3*fact(2)
return n*fact(n-1) 5*4*3*2*fact(1)
n=int(input("enter no. to find fact:")) 5*4*3*2*1
f=fact(n)
print("Fact is",f)
Output
enter no. to find fact:5
Fact is 120
5*fact(5-1) 5*fact(5-1)
5*4*fact(4-1) 5*4*fact(4-1)
5*4*3*fact(3-1) 5*4*3*fact(3-1)
5*4*3*2*fact(2-1) 5*4*3*2*fact(2-1)
5*4*3*2*1 5*4*3*2*1
Sum of n numbers using recursion
def sum(n):
if(n==0):
return 0 N=5
else: 5+sum(4)
return n+sum(n-1) 5+4+sum(3)
n=int(input("enter no. to find sum:")) 5+4+3+sum(2)
sum=sum(n) 5+4+3+2+sum(1)
print(sum) 5+4+3+2+1+sum(0)
N=1
Output 1+sum(0)
enter no. to find sum:10 1+0=1
output is 55
# Function to combine two function which it accepts as argument
def composite_function(f, g): Trace Program
return lambda x : f(g(x)) composite_function(multiply, add)
add_(multiply(5))
# Function to add 2 Order of Execution:
def add(x): lambda x : f(g(x))
g(5) =add(5)->return 7
return x + 2 f(7)= multiply(7)->return 14
# Function to multiply 2
def multiply(x): OUTPUT:
14
return x * 2
# Composite function returns a lambda function. Here add_multiply
# will store lambda x : multiply(add(x))
add_multiply = composite_function(multiply, add)
print("Adding 2 to 5 and multiplying the result with 2: ", add_multiply(5))
Strings:
• Strings
• String slices
• Immutability
• String functions and methods
• String module
Strings:
• String is defined as sequence of characters represented in quotation
marks (either single quotes ( ‘ ) or double quotes ( “ ).
• An individual character in a string is accessed using a index.
• The index should always be an integer (positive or negative).
• A index starts from 0 to n-1.
• Strings are immutable i.e. the contents of the string cannot be changed after it
is created.
• Python will get the input at run time by default as a string.
• Python does not support character data type. A string of size 1 can be treated
as characters.
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
Immutability:
• Python strings are “immutable” as they cannot be changed after they are
created.
• Therefore [ ] operator cannot be used on the left side of an assignment.

Example Output
a="python" TypeError: 'str' object does not support item
a[1]="m" assignment
a="python" TypeError: 'str' object doesn't support item deletion
del a[1]
a="python" The string get deleted
del a
string built in functions and methods:
A method is a function that “belongs to” an object.
Syntax to access the method
Stringname.method()
a=”happy birthday”
here, a is the string name.
String modules:
• A module is a file containing Python definitions, functions, statements.
• Standard library of Python is extended as modules.
• To use these modules in a program, programmer needs to import the
module.
• Once we import a module, we can reference or use to any of its functions
or variables in our code.
• There is large number of standard modules also available in python.
• Standard modules can be imported the same way as we import our user-
defined modules.
Syntax:
import module_name
Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)
List as array:
Array:
• Array is a collection of similar elements.
• Elements in the array can be accessed by index.
• Index starts with 0.
• Array can be handled in python by module named array.
• To create array have to import array module in the program.
Syntax :
import array

Syntax to create array:


Array_name = module_name.function_name(‘datatype’,[elements])
Methods in array
a=[2,3,4,5]
example:
a=array.array(‘i’,[1,2,3,4]) a=[10,20,30,40]
where, a- array name Sum=10+20+30+40=
array- module name
i- integer datatype
Example: sum=0
Program to find sum of array elements sum=0+1=1
import array sum=1+2=3
sum=0 Sum=3+3=6
a=array.array('i',[1,2,3,4]) Sum=6+4=10
for i in a:
sum=sum+i
print(sum)
Output
10
Convert list into array:
fromlist() function is used to append list to array. Here the list act like a array.
Syntax:
arrayname.fromlist(list_name)
Example: Program to convert list into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Output
35
ILLUSTRATIVE PROGRAMS:

Square root using newtons method:

def sqrt(n):
approx=0.5*n
accurate=0.5*(approx+n/approx)
while (accurate!=approx):
approx=accurate
accurate=0.5*(approx+n/approx)
return approx
print("The square root is",sqrt(3))

Output:
enter number to find Sqrt: 9
ILLUSTRATIVE PROGRAMS:
GCD of two numbers
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a % b)
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print(gcd(a, b))
output
Enter the first number54
Enter the second number24
6
ILLUSTRATIVE PROGRAMS:
Exponent of number
base= int(input("Enter base:"))
exp= int(input("Enter exponential value:"))
power=1
for i in range(1, exp+1):
power=power*base
print("power of a number is", power)
Output:
Enter base:6
Enter exponential value:4
Result:1296
ILLUSTRATIVE PROGRAMS:
Sum of array elements:
a=[2,3,4,5,6,7,8]
sum=0
for i in a:
sum=sum+i
print(“The sum is",sum)

output:
The sum is 35
ILLUSTRATIVE PROGRAMS:
Linear search
a=[20,30,40,50,60,70,89] Output
Enter the element to be searched 40
Element is found at position 2
print(a)
search=int(input(“Enter the element to be searched:"))

for i in range(0,len(a),1):

if(search==a[i]):

print("element found at", i)


break

else: print("not found")


Binary search
a=[20, 30, 40, 50, 60, 70, 89]

print(a)
Output
search=int(input(“Enter the element to be searched:"))
Enter the Element to be Search: 30
start=0 Element 30 Found at Position 1
stop=len(a)-1

while(start<=stop):

mid=(start+stop)//2

if(search==a[mid]):

print("element found at",mid+1)

break

elif(search<a[mid]):

stop=mid-1

else:

start=mid+1

else:

print("not found")

You might also like