for more updates visit: www.python4csip.
com
Revision Tour
Control Flow Statements in Python
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Types of Statement in Python
Statements are the instructions given to
computer to perform any task. Task may be
simple calculation, checking the condition or
repeating action.
Python supports 3 types of statement:
Empty statement
Simple statement
Compound statement
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Empty Statement
It is the simplest statement i.e. a statement
which does nothing. It is written by using
keyword – pass
Whenever python encountered pass it does
nothing and moves to next statement in flow
of control
Required where syntax of python required
presence of a statement but where the logic
of program does. More detail will be explored
with loop.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Simple Statement
Any single executable statement in Python is
simple statement. For e.g.
Name = input(“enter your name “)
print(name)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Compound Statement
It represent group of statement executed as
unit. The compound statement of python are
written in a specific pattern:
Compound_Statement_Header :
indented_body containing multiple
simple or compound statement
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Compound Statement has:
Header which begins with keyword/function
and ends with colon(:)
A body contains of one or more python
statements each indented inside the header
line. All statement in the body or under any
header must be at the same level of
indentation.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Statement Flow Control
In python program statement may execute in
a sequence, selectively or iteratively. Python
programming support 3 Control Flow
statements:
1. Sequence
2. Selection
3. Iteration
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
if Statement of Python
‘if’ statement of python is used to execute
statements based on condition. It tests the
condition and if the condition is true it
perform certain action, we can also provide
action for false situation.
if statement in Python is of many forms:
if without false statement
if with else
if with elif
Nested if
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Simple “if”
In the simplest form if statement in Python
checks the condition and execute the
statement if the condition is true and do
nothing if the condition is false.
Syntax: All statement
belonging to if
if condition: must have same
indentation level
Statement1
Statements ….
** if statement is compound statement having
header and a body containing intended
statement.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Points to remember with “if”
It must contain valid condition which
evaluates to either True or False
Condition must followed by Colon (:) , it is
mandatory
Statement inside if must be at same
indentation level.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Input monthly sale of employee and give bonus of 10%
if sale is more than 50000 otherwise bonus will be 0
bonus = 0
sale = int(input("Enter Monthly Sales :"))
if sale>50000:
bonus=sale * 10 /100
print("Bonus = " + str(bonus))
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
if with else
if with else is used to test the condition and if
the condition is True it perform certain
action and alternate course of action if the
condition is false.
Syntax:
if condition:
Statements
else:
Statements
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Input Age of person and print whether the person is
eligible for voting or not
age = int(input("Enter your age "))
if age>=18:
print("Congratulation! you are eligible for voting ")
else:
print("Sorry! You are not eligible for voting")
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
if with elif
if with elif is used where multiple chain of condition is to
be checked. Each elif must be followed by condition: and
then statement for it. After every elif we can give else
which will be executed if all the condition evaluates to
false
Syntax:
if condition:
Statements
elif condition:
Statements
elif condition:
Statements
else:
Statement
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Input temperature of water and print its physical state
temp = int(input("Enter temperature of water "))
if temp>100:
print("Gaseous State")
elif temp<0:
print("Solid State")
else:
print("Liquid State")
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Nested if
In this type of “if” we put if within another if as a
statement of it. Mostly used in a situation where we
want different else for each condition. Syntax:
if condition1:
if condition2:
statements
else:
statements
elif condition3:
statements
else:
statements
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Storing Condition
In a program if our condition is complex and it
is repetitive then we can store the condition
in a name and then use the named condition
in if statement. It makes program more
readable.
For e.g.
x_is_less=y>=x<=z
y_is_less=x>=y<=z
Even = num%2==0
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Python Loop Statements
To carry out repetition of statements Python
provide 2 loop statements
Conditional loop (while)
Counting loop (for)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
range() function
Before we proceed to for loop let us
understand range() function which we will
use in for loop to repeat the statement to n
number of times.
Syntax:
range(lower_limit, upper_limit)
The range function generate set of values
from lower_limit to upper_limit-1
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
range() function
For e.g.
range(1,10) will generate set of values from
1-9
range(0,7) will generate [0-6]
Default step value will be +1 i.e.
range(1,10) means (1,2,3,4,5,6,7,8,9)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
range() function
To change the step value we can use third
parameter in range() which is step value
For e.g.
range(1,10,2) now this will generate value
[1,3,5,7,9]
Step value can be in –ve also to generate set
of numbers in reverse order.
range(10,0) will generate number as
[10,9,8,7,6,5,4,3,2,1]
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
range() function
To create list from ZERO(0) we can use
range(10) it will generate
[0,1,2,3,4,5,6,7,8,9]
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Operators in and not in
The operator in and not in is used in for loop
to check whether the value is in the range /
list or not
For e.g.
>>> 5 in [1,2,3,4,5]
True
>>> 5 in [1,2,3,4]
False
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
>>>’a’ in ‘apple’
True
>>>’national’ in ‘international’
True
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
for loop
for loop in python is used to create a loop to
process items of any sequence like List, Tuple,
Dictionary, String
It can also be used to create loop of fixed
number of steps like 5 times, 10 times, n
times etc using range() function.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example – for loop with List
School=["Principal","PGT","TGT","PRT"]
for sm in School:
print(sm)
Example – for loop with Tuple
Code=(10,20,30,40,50,60)
for cd in Code:
print(cd)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Let us understand how for loop
works
Code=(10,20,30,40,50,60)
for cd in Code:
print(cd)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
for loop with string
for ch in ‘Plan’:
print(ch)
The above loop product output
P
l
a
n
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
for with range()
Let us create a loop to print all the natural number from 1 to
100
for i in range(1,101):
print(i,end='\t')
** here end=‘\t’ will cause output to appear without
changing line and give one tab space between next output.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
while loop
While loop in python is conditional loop
which repeat the instruction as long as
condition remains true.
It is entry-controlled loop i.e. it first check the
condition and if it is true then allows to enter
in loop.
while loop contains various loop elements:
initialization, test condition, body of loop
and update statement
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
while loop elements
1. Initialization : it is used to give starting
value in a loop variable from where to start
the loop
2. Test condition : it is the condition or last
value up to which loop will be executed.
3. Body of loop : it specifies the
action/statement to repeat in the loop
4. Update statement : it is the increase or
decrease in loop variable to reach the test
condition.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example of simple while loop
i=1
while i<=10:
print(i)
i+=1
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Jump Statements – break & continue
break statement in python is used to terminate
the containing loop for any given condition.
Program resumes from the statement
immediately after the loop
Continue statement in python is used to skip
the statements below continue statement
inside loop and forces the loop to continue
with next value.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example – break
for i in range(1,20):
if i % 6 == 0:
break
print(i)
print(“Loop Over”)
The above code produces output
1
2
3
4
5
Loop Over
when the value of i reaches to 6 condition will becomes True and
loop will end and message “Loop Over” will be printed
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example – continue
for i in range(1,20):
if i % 6 == 0:
continue
print(i, end = ‘ ‘)
print(“Loop Over”)
The above code produces output
1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19
Loop Over
when the value of i becomes divisible from 6, condition will
becomes True and loop will skip all the statement below
continue and continues in loop with next value of iteration.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Loop .. else .. Statement
Loop in python provides else clause with loop
also which will execute when the loop
terminates normally i.e. when the test
condition fails in while loop or when last value
is executed in for loop but not when break
terminates the loop
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example (“else” with while)
i=1 Output
1
while i<=10: 2
3
print(i) 4
5
i+=1 6
7
8
else: 9
10
print("Loop Over") Loop Over
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example (“else” with for)
names=["allahabad","lucknow","varanasi","kanpur","agra","ghaziabad"
,"mathura","meerut"]
city = input("Enter city to search: ")
for c in names:
if c == city:
print(“City Found")
break Output
else: Enter city to search : varanasi
City Found
print("Not found") Enter city to search : unnao
Not found
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Generating Random numbers
Python allows us to generate random number
between any range
To generate random number we need to
import random library
Syntax: (to generate random number)
random.randint(x,y)
it will generate random number between x to y
For e.g. : random.randint(1,10)
Refer to code page no. 156
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
STRING MANIPULATION
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Program to read string and
print in reverse order
string1 = input("Enter any string ")
print("The Reverse of ", string1 , " is :")
length=len(string1)
for ch in range(-1,(-length-1),-1):
print(string1[ch])
The above code will print
Enter any string: karan
n
a
r
a
k
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Program to input string and
print short form
string=input("Enter any string ")
print(string[0],".",end='')
for ch in range(1,len(string)):
if string[ch]==' ':
print(string[ch+1],".",end='')
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
String operators
Two basic operators + and * are allowed
+ is used for concatenation (joining)
e.g. “shakti” + “man” OUTPUT: shaktiman
* Is used for replication (repetition)
e.g. “Bla” * 3 OUTPUT: BlaBlaBla
Note: you cannot multiply string and string using *
Only number*number or string*number is allowed
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
MEMBERSHIP OPERATORS
Membership operators (in and not in) are used
to check the presence of character(s) in any
string.
Example Output
‘a’ in ‘python’ False
‘a’ in ‘java’ True
‘per’ in ‘operators’ True
‘men’ in ‘membership’ False
‘Man’ in ‘manipulation’ False
‘Pre’ not in ‘presence’ True
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Comparison operators
We can apply comparison operators (==,
!=,>,<,>=,<=) on string. Comparison will be
character by character.
str1=„program‟
Comparison of
str2=„python‟ string will be
str3=„Python‟ based on ASCII
code of the
characters
Example Output
str1==str2 False
Characters Ordinal/
str1!=str2 True
ASCII code
str2==„pyth True A-Z 65-90
on‟
a-z 97-122
str2>str3 True
0-9 48-57
str3<str1 True
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
DETERMINING ORDINAL /
UNICODE OF A SINGLE
CHARACTER
Python allows us to find out the ordinal position
single character using ord() function.
>>>ord(‘A’) output will be 65
We can also find out the character based on the
ordinal value using chr() function
>>>chr(66) output will be ‘B’
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
String slicing
>>> str1="wonderful" >>> str1[3:3]
>>> str1[0:6] ''
'wonder' >>> str1[3:4]
>>> str1[0:3] 'd'
'won' >>> str1[-5:-2]
>>> str1[3:6] 'erf'
'der' >>> str1[:-2]
>>> str1[-1:-3] 'wonderf'
'' >>> str1[:4]
>>> str1[-3:-1] 'wond‘
'fu' >>> str1[-3:] Reverse
>>> str1[-3:0] 'ful‘ of string
'‘ >>>str1[::-1]
>>>str1[0::2] lufrednow
‘Wnefl’
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Interesting string slicing
For any index position n: str1[:n]+str1[n:] will
give you the original string
>>>str1=“wonderful”
>>>str1[:n]+str[n:] output will be wonderful
String slicing will never return error even if you
pass index which is not in the string . For e.g.
>>>str1[10] will give error, but
>>>str1[10:15] will not give error but
return empty string
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Python string manipulation
function
Function name Purpose Example
String.capitalize() Return a copy of string >>>’computer’.capitalize()
with first character as Computer
capital
String.find(str[,start[,end]]) Return lowest index of str Str=“johny johny yes
in given string , -1 if not papa”
found Sub=“johny”
Str.find(Sub)
0
Str.find(Sub,1)
6
Str.find(‘y’,6,11)
10
Str.find(‘pinky’)
-1
String.isalnum() Return True if the string is ‘hello123’.isalnum()
alphanumeric character True
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Python string manipulation
function
Function name Purpose Example
String.isalnum() S=“[email protected]
S.Isalnum()
False
String.isalpha() Return True if string Str1=“hello”
contains only alphabets Str2=“hello123”
characters Str1.isalpha()
True
Str2.isalpha()
False
String.isdigit() Return True if string s1=“123”
contains only digits s1.isdigit()
True
Str2.isdigit()
False
String.islower() Return True if all Str1.islower()
character in string is in True
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & lower case
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Python string manipulation
function
Function name Purpose Example
String.isspace() Return True if only S=“ “
whitespace characters in S.isspace()
the string True
S2=‘’
S2.isspace()
False
String.upper() Return True if all S=“HELLO”
characters in the string S.isupper()
are in upper case True
String.lower() Return copy of string S=“INDIA”
converted to lower case S.lower()
characters india
String.upper() Return copy of string S=“india”
converted to upper case S.lower()
characters INDIA
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Python string manipulation
function
Function name Purpose Example
String.lstrip([chars]) Returns a copy of string with string=" hello"
leading characters removed. string.lstrip()
If no characters are passed then it 'hello'
removes whitespace string2="National"
It removes all combination of given string2.lstrip('nat')
characters i.e. if we pass “The” National
then its combination – The, Teh, string2.lstrip('Nat')
heT, ehT, he, eh, h, e, etc will be ional
removed string2.lstrip('at')
National
string2.lstrip('Na')
tional
string2.lstrip('atN')
ional
String.rstrip([chars]) Returns a copy of string with “saregamapadhanisa”.rstrip
trailing characters removed. Rest is (‘ania’)
same as lstrip saregamapadha
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR