IF-ELIF Statements
IF-ELIF Statements
If condition is true, if-block statement(s) are executed and if the condition is false, else block
statement(s) are executed.
if boolean_expression:
statement(s)
else:
statement(s)
Note:
1) If and else are in line
2) Indentation for if statements and else statements
3) : after Boolean expression and else
Example 1:
a = 2
b = 4
if a<b:
print(a, 'is less than', b)
else:
print(a, 'is not less than', b)
output
2 is less than 4
Python if...elif...else Statement
Syntax of if...elif...else
if boolean_expression_1:
statement(s)
elif boolean_expression_2:
statement(s)
elif boolean_expression_3:
statement(s)
else
statement(s)
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
a = 2
b = 4
if a<b:
print(a, 'is less than', b)
elif a>b:
print(a, 'is greater than', b)
else:
print(a, 'equals', b)
Output
2 is less than 4