Python Control Flow and Functions Guide
Python Control Flow and Functions Guide
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false
and 1 or True for true, unless otherwise stated.
3.2 OPERATORS
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
56
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Membership Operators
Identity Operators
[Link]
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
57
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
[Link]
a = 21
b = 10
c=0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
58
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
Output
59
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c =2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
60
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
61
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below
62
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"
a=2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
Output:
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below:
63
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"
if ( a is not b ):
print "Line 4 - a and b do not have same identity"
else:
print "Line 4 - a and b have same identity"
Output:
The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation (raise to the power)
Complement, unary plus and minus (method names for the
~+- last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
64
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
Output:
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
3.3.1 if statement
65
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Syntax:
if expression:
statements
Expression is a logical expression which tests and results either true or false
Flowchart:
[Link]
number=10
if number>0:
print(number," is a positive number")
number=-1
if number>0:
print(number," is a positive number")
Output:
10 is a positive number
If there are two statements to be executed alternatively, then if-else statement is used.
If the condition is true, then true statements are executed otherwise statements of else
part is executed.
Syntax: Flowchart:
if expression:
statements
else:
statements
66
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
number=28
if number%2==0:
print(number," is a even number")
else:
print(number," is a odd number")
Output:
28 is a even number
Syntax:
if expression:
body of if
elif expression:
body of elif
--
--
else:
body of else
Flowchart:
false
Expression
Expression
True
Body of if Body of elif Body of else
67
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
a=float(input("Enter the number:"))
if a>0:
print("The given number is a positive number")
elif a==0:
print("The given number is Zero")
else:
print("The given number is negative number")
Output:
Enter the number:-1
The given number is negative number
>>>
Enter the number:0
The given number is Zero
>>>
Enter the number:100
The given number is a positive number
68
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
When there are more than two possibilities it requires more than two branches.
Syntax:
if expression:
body of if
elif expression:
body of elif
else:
body of else
Flowchart:
[Link]
value=10
if value==20:
print("Got a true value ",value)
elif value==15:
print("Got a true value ",value)
elif value==10:
print("Got a true value ",value)
else:
print("Got a false value ",value)
print("Program Over")
Output:
>>>Got a true value 10
Program Over
69
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
3.4 ITERATION
Repeated execution of set of statements until a specified condition becomes true is called
as iteration.
Types:
1. while
2. for
Syntax:
while expression:
statement(s)
Flowchart:
[Link]
count=0
while(count<5):
print("the count value is",count)
count=count+1
Output:
the count value is 0
the count value is 1
the count value is 2
70
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
x=-2
y=2
while x<=y:
print("x=",x)
x=x+1
while(x<=0):
print("x is negative")
x=x+1
Output:
x= -2
x is negative
x is negative
x= 1
x= 2
Syntax:
for val in sequence:
Body of for
Val is a variable that takes value of the item inside the sequence on each iteration.
Loop continues until the last item in the sequence is reached.
71
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
For loop contains initialization & condition part, but increment and decrement
need not to be defined in python.
Flowchart:
[Link]
word = "computer"
for letter in word:
print(letter)
Output:
c
o
m
p
u
t
e
r
[Link]
num=[20,30,40]
for i in num:
print("The value of i is",i)
Output:
The value of i is 20
72
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
The value of i is 30
The value of i is 40
[Link]
for x in range(1,3):
for y in range(1,3):
print(x,"*",y,"=",x*y)
Output:
1*1=1
1*2=2
2*1=2
2*2=4
3.4.5 range()
This function is used for iteration using for loop
Default initial value of range() is 0.
This returns a list of values.
Syntax:
range([start],stop,[step])
[Link]
73
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
xrange()
This works similar to range() but returns a xrange object.
This is used when huge billion amount of values are to be generated.
This works only in Pyhton 2v.
It uses less memory.
74
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Syntax:
xrange([start],stop,[stop])
[Link]
Output:
75
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Syntax: continue
Flowchart:
[Link]
for x in range(1,10):
if x==5:
continue
print("x=",x)
Output:
x= 1
x= 2
x= 3
x= 4
x= 6
x= 7
x= 8
x= 9
3.5.2 break
It brings control out of the loop.
76
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
Syntax:
break
Flowchart:
[Link]
for x in range(1,10):
if x==5:
break
print("x=",x)
Output:
x= 1
x= 2
x= 3
x= 4
3.5.3 pass
The pass statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute.
Used to write empty loops.
Syntax:
pass
77
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
for letter in "python":
if letter=="h":
pass
print("pass block")
print("letter=",letter)
Output:
letter= p
letter= y
letter= t
pass block
letter= h
letter= o
letter= n
needs return
Fruitful Function
[Link]
def square(b):
c=b*b
return c
b=5
result=square(b)
print("The square of ",b," is ",result)
Output:
The square of 5 is 25
>>>
78
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
79
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
100 Black
100 Black
Output:
20 15
5 15
80
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
4
>>>
Output:
value inside function: 10
value when return is used: 10
value outside function: 20
3.6.4 Composition
The ability of calling one function from within another function is called
as composition.
[Link]
#Program to find square of a number
c=float(input("Enter a value:"))
d=c**2
81
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
print(d)
Output:
Enter a value:2.5
6.25
3.6.5 Recursion
Recursion is a process of calling a function by itself again and again until some
condition is satisfied.
A recursive function must have
1. A statement to test whether the function is calling itself again.
2. A statement that calls the function itself must be an argument.
3. A conditional statement
4. A return statement.
Advantages:
1. The code look clean and elegant.
2. Large problems broken down into small problems
Disadvantages:
1. Logic is hard to follow.
2. It takes more memory.
3. It is hard to debug.
[Link]
#Program to find factorial using recursion
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
82
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
print(factorial(5))
Output:
120
>>>
[Link]
#Program to find Fibonacci series till 10 terms
def fibo(n):
if n<=1:
return n
else:
return(fibo(n-1)+fibo(n-2))
terms=10
print("Fibonacci series")
for i in range(terms):
print(fibo(i))
Output:
Fibonacci series
0
1
1
2
3
5
8
13
21
34
3.7 STRINGS
It is a sequence of characters treated as a single data item enclosed within
either single or double quotes or even triple quotes.
[Link]
example='I am found of chocolates'
83
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
print(example)
example="I am found of ice creams"
print(example)
example='''I am found of cakes too'''
print(example)
example=''
print(example)
Output:
I am found of chocolates
I am found of ice creams
I am found of cakes too
>>>
[Link]
#string with single quote
var1='python'
print(var1)
#string with double quote
var1="python"
print(var1)
#string with triple quote
var1="""Python is one of the programming
language"""
print(var1)
Output:
python
python
Python is one of the programming
Language
3.7.1 String Slices
A portion or a filtered part of a string is called as slice.
Slice is used to take sub parts of either from list or string.
Syntax:
Substring=originalstring[start:end]
84
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Example
0 1 2 3 4
B L A C K
-5 -4 -3 -2 -1
[Link]
Output:
Live
e and let live
Live a
Live and let live
>>>
[Link]
str='Python Programming'
print("The Given String is",str)
print("The first character in the String is",str[0])
print("The character starting from 3rd to 5th position is",str[2:5])
print("The String starting from 3rd character is",str[2:])
print("The last character of the string is",str[-1])
print("The String from negative indices is",str[-5:])
85
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
The Given String is Python Programming
The first character in the String is P
The character starting from 3rd to 5th position is tho
The String starting from 3rd character is thon Programming
The last character of the string is g
The String from negative indices is mming
3.7.2 Immutability
Strings in python are immutable i,e after created it cannot be changed.
No assignments can be done later but updation is possible.
[Link]
#NO ITEM ASSIGNMENT IN PYTHON
var1="python"
var1[2]="T"
Output:
Traceback (most recent call last):
var1[2]="T"
TypeError: 'str' object does not support item assignment
[Link]
#NO ITEM DELETION IN PYTHON
var1="python"
del var1
Output:
Traceback (most recent call last):
TypeError: 'str' object does not support item deletion
[Link]
var1="python"
del var1
print(var1)
86
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
Traceback (most recent call last):
print(var1)
NameError: name 'var1' is not defined
[Link]
v1 = 'Are you okay!'
print("Updated String:",v1[:13] +' baby')
Output:
Updated String: Are you okay! Baby
Assume string variable a holds 'Hello' and variable b holds ' boys ', then −
[Link]
a='I hate bitter food'
b="badly"
print("The Concatenation of the String is:",a+b)
print("The Repetition of the String is:",a*2)
print("The Slicing of the string is:",a[2])
print("The Slicing of the string is:",a[3:6])
87
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
The Concatenation of the String is: I hate bitter foodbadly
The Repetition of the String is: I hate bitter foodI hate bitter food
The Slicing of the string is: h
The Slicing of the string is: ate
The membership operator of the string is: True
The membership operator of the string is: True
>>>
3.7.4 String formatting Operator
Symbol used is %.
It is mainly used for print()
Format Symbol Conversion
%c character
%o octal integer
88
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
1. capitalize()function
This returns a string with first letter in capital letters.
Syntax:
[Link]()
89
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
The result of capitalize function is Python programming
[Link]() function
This method returns a string padded with specified character to fill.
It doesnot modify the original string.
Syntax:
[Link](width[,fillchar])
where width is length of the string & fill char is character to be filled.
[Link]
str="I lost my books!"
print([Link](18,'a'))
Output:
aI lost my books!a
[Link]() function
This method removes all case variations in a string.
It is used for caseless matching.
It doesnot take any parameters.
Syntax:
[Link]()
[Link]
a1="PYTHON programming"
Output:
>>>
[Link]() function
[Link](substring,start= … , end=…)
90
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
[Link]
var1="Engineering Knowledge"
Output:
>>>
[Link]() function
This method returns True if a string ends with the specified suffix otherwise return
false.
Syntax:
[Link](suffix[,start[,end]])
[Link]
t="English is just a language not knowledge"
result=[Link](" knowledge")
print(result)
result=[Link](" knowledge.")
print(result)
result=[Link]("not")
print(result)
Output:
True
False
False
>>>
[Link]() function
This function is used to return the lowest index of the substring (if found) otherwise
returns -1.
Syntax:
[Link](sub[,start[,end]])
[Link]
var1="PYTHON programming"
91
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
The result of find function is 0
The result of find function is -1
>>>
[Link]()function
[Link](posarg1,posarg2,…..,keyarg0=v0,keyarg1=v1,….)
[Link]
This function returns the index of a substring inside the string otherwise it raises a
value error exception.
Syntax:
[Link](sub[,start[,end]])
[Link]
result=[Link]('to python')
92
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
[Link]() function
where separator is the place where the split occurs & max is maximum number of splits.
[Link]
new='abcdef'
items='black,blue,green'
print([Link]())
print([Link](','))
Output:
['abcdef']
[Link]()function
This method returns True if a string starts with the specified prefix otherwise returns
false.
Syntax:
[Link](prefix[,start[,end]])
[Link]
t1="Computer Language"
r1=[Link]('Language',9)
print(r1)
r1=[Link]('Language',2)
print(r1)
Output:
True
False
>>>
93
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
import string
s="Welcome to the world of Robotics"
print("Upper case:",[Link](s))
print("Lower case:",[Link](s))
print("Split:",[Link](s))
print("Join:"," ".join(s))
print("Replace:",[Link](s,"Robotics","Innovation"))
print("Find:",[Link](s,"world"),[Link](s,"of"))
print("Count:",[Link](s,"t"))Output:
Output:
Upper case: WELCOME TO THE WORLD OF ROBOTICS
Lower case: welcome to the world of robotics
Split: ['Welcome', 'to', 'the', 'world', 'of', 'Robotics']
Join: W e l c o m e t o t h e w o r l d o f R o b o t i c s
Replace: Welcome to the world of Innovation
Find: 15 21
Count: 3
94
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Example
a=[1,2,5,8,9]
b=[“a”,”g”,”r”]
c=[67,”red”,90,”yellow”]
[] are used to access values in a list for slicing along with the index or indices to
obtain value available at that index.
Slice[m:n] where m is starting index which is included & n in end index which is
excluded.
[Link]
l1=['English','Maths',1000,3000]
l2=[10,20,30,40,50]
print(l1[0])
print(l2[2:4])
print(l1[:-2])
print(l2[-6])
Output:
English
[30, 40]
['English', 'Maths']
Traceback (most recent call last):
File "python", line 6, in <module>
IndexError: list index out of range
Single or multiple elements can be updated in a list by giving the slice on the left-
hand side of the assignment operator and also add the elements in a list with the
append() method.
[Link]
s=['Red','green','Blue','yellow','Purple']
print("value at index 2:",s[2])
95
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
s[2]='Lavender'
print(s)
[Link]('Orange')
print(s)
Output:
value at index 2: Blue
['Red', 'green', 'Lavender', 'yellow', 'Purple']
['Red', 'green', 'Lavender', 'yellow', 'Purple', 'Orange']
[Link]
s=['Red','green','Blue','yellow','Purple']
print(s)
del s[2]
print(s)
[Link]('yellow')
print(s)
Output:
['Red', 'green', 'Blue', 'yellow', 'Purple']
['Red', 'green', 'yellow', 'Purple']
['Red', 'green', 'Purple']
96
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
result=gcd(a,b)
print("GCD is:",result)
Output:
3. Exponentiation of a number
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Output:
Enter base: 3
Enter exponential value: 2
Result: 9
5. Linear search
list=[8,4,10,54,89]
search=int(input("Enter the number to search:"))
length=len(list)
for i in range(0,length):
if list[i]==search:
print(search," is found at the position ",i+1)
break
else:
print("Number not found")
97
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING DEPT OF CSE, CKCET
Output:
6. Binary search
def binarysearch(sortedlist,n,x):
start = 0
end = n - 1
while(start <= end):
mid = (start + end)//2
mid=int(mid) #gives mid a rounded value if it is in float
if (x == sortedlist[mid]):
return mid
elif(x < sortedlist[mid]):
end = mid - 1
else:
start = mid + 1
return -1
n =5
sortedlist = [10,23,38,41,50]
98