Python Week 3
Python Week 3
WEEK -3
Control flow: The program instructions are executed sequentially i.e, one after the
Control Flow: after.
Conditional • If you want to skip some instructions or you want to change the flow of the
blocks program, it is done by conditional blocks.
Conditional blocks / statements in Python are
• if statement
• elif statement
• else statement
• Nested if
• The comparison operators such as ==, !=, > Ex: a=30
if statement , <, <=,>= are used to form conditions. b=20
• Ex: a == b, a != b, a < b, a > b etc.. if a > b:
• These conditions are used in if statement. print(“a is greater than b”)
In the above example
• if is keyword
• a>b is the condition to be tested
How if works?
• if the condition a>b is true, then the statement print(“a is greater than b”) is
executed .
• if the condition a>b is false, then the statement print(“a is greater than b”) is not
executed .
General format
if condition:
Statement/ block of statements
Statement
• if the condition is true, then the Statement/ block of statements are executed .
• if the condition is false, then the Statement/ block of statements are skipped and
statement after the if block is executed.
Ex: n1=30
n2=20
if n1 > n2:
print(“n1 is greater than n2”)
Ex: if 5 == 5
print(“both are equal”)
Ex: n1=30 , n2=20
if n1 != n2:
print(“n1 is not equal to n2”)
else statement • else statement is used when all the Ex: n1=10
previous conditions are false. n2=20
General format if n1 > n2:
if condition: print(“n1 is greater than n2”)
statement1 else:
else: print(“n2 is greater that n1”)
statement 2
Nested if • Placing an if statement inside Ex: x=31
statement another if is called nested if. if x > 10:
print(“x is greater than 10”)
if x > 20:
print(“x is greater than 20”)
if x > 20:
print(“x is greater than 30”)
Sample Programs
n1=10
n2=10
if n1 > n2:
print(“n1 is greater than n2”)
elif n1 == n1:
print(“n1 is equal to n2”)
if x > 30:
print(“x is greater than 30”)