Python If...Else
Along with the if statement,else keyword can also be optionally used.
It provides an alternate block of statements to be executed if the Boolean expression (in if statement) is not true.
This flowchart shows how else block is used.
If the expr is True, block of stmt 1,2,3 is executed then the default flow continues with stmt7. However, the If expr is False, block stmt 4,5,6 runs then the default flow continues.
Syntax
if expr==True: stmt1 stmt2 stmt3 else: stmt4 stmt5 stmt6 Stmt7
Python implementation of the above flowchart is as follows:
Example
age=int(input("Enter the age : ")) if age>=18: print("Eligible to Vote") else: print("Not eligible to Vote") Output Enter the age :25 Eligible to Vote
Elif
The elif
keyword is a way of saying "if the previous condition is not true,then try this condition".
Example
a=30 b=90 if a>b: print("a is greater") elif a==b: print("Both are equal") else: print("b is greater") Output b is greater