if expression1 :
statement_1
statement_2
....
elif expression2 :
statement_3
statement_4
....
elif expression3 :
statement_5
statement_6
....
else :
statement_7
statement_8
In the above case Python evaluates each expression (i.e. the condition) one by one and if a true condition is found the statement(s) block under that expression will be executed. If no true condition is found the statement(s) block under else will be executed.
>>> var1 = 1+2j
>>> if (type(var1) == int):
print("Type of the variable is Integer")
elif (type(var1) == float):
print("Type of the variable is Float")
elif (type(var1) == complex):
print("Type of the variable is Complex")
elif (type(var1) == bool):
print("Type of the variable is Bool")
elif (type(var1) == str):
print("Type of the variable is String")
elif (type(var1) == tuple):
print("Type of the variable is Tuple")
elif (type(var1) == dict):
print("Type of the variable is Dictionaries")
elif (type(var1) == list):
print("Type of the variable is List")
else:
print("Type of the variable is Unknown")
Type of the variable is Complex
>>>
In general nested if-else statement is used when we want to check more than one conditions. Conditions are executed from top to bottom and check each condition whether it evaluates to true or not. If a true condition is found the statement(s) block associated with the condition executes otherwise it goes to next condition. Here is the syntax :
if expression1 :
if expression2 :
statement_3
....
else :
statement_4
....
else :
statement_5
....
>>> a=10
>>> if a>=20:
print ("Condition is True")
else:
if a>=15:
print ("Checking second value")
else:
print ("All Conditions are false")
All Conditions are false
>>>