By: Archana Shukla and Rajesh Shukla
Flow of execution
The way in which the statements are executed defines the flow of execution in a python program. It is categorized in the following types:
Sequential statements
In this type the statements are executed one after the other from the very first statement to the last statement.
Example 1 : program to compute area of a circle
r=int(input('enter the radius of a circle: ')) area=3.14*r*r print('area of a circle is : ',area)
Output
enter the radius of a circle: 2
area of a circle is : 12.56
>>>
Selection / conditional statements
These type of statements are executed on the basis of the given condition whether the condition is true or false. If statement is used for decision making or selection in programming.
Syntax:
if (test expression):
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True.
Example
age=int(input('enter your age :')) if age>=18: print('eligible for voting')
Output
enter your age :20
eligible for voting
>>>
Python If…else statement
The if..else statement evaluates test expression and will execute body of if only when test condition is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Example
age=int(input('enter your age :')) if age>=18: print('eligible for voting') else: print('not eligible')
Output
enter your age :12
not eligible
>>>
Python if…elif…else
Syntax
if (test expression):
Body of if
elif (test expression):
Body of life
else:
Body of else
Here else is optional. Number of elif depends on number of conditions
Example: To print the name of the week day.
d=int(input("Enter days no (1..7)")) if(d==1): print("Sun") elif(d==2): print("Mon") elif(d==3): print("Tue") elif(d==4): print("Wed") elif(d==5): print("Thur") elif(d==6): print("Fri") elif(d==7): print("Sat") else: print("Invalid day number")
Nested if … else statement
It allows us to check for multiple test expressions and execute different codes for more than two conditions.
Syntax
if (test expression):
Body of if
else:
if (test expression):
Body of if
else:
Body of else
Example: To check whether the number is +ve or -ve or 0.
a=int(input("Enter any no ")) if(a==0): print("number is zero") else: if(a>0): print("number is +ve") else: print("number is -ve")