IF… ELSE Statement:
If condition is true, if-block statement(s) are executed and if the condition is false, else block
statement(s) are executed.
The syntax of Python if-else statement is given below.
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
The syntax of python elif statement is as shown below.
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.
If all the conditions are False, the body of else is executed.
Example: Python elif
We take two numbers, and have an if-elif statement. We are checking two conditions, a<b and a>b.
Which ever evaluates to True, when executed sequentially, the corresponding block is executed.
In the following program, a<b returns True, and therefore the if block is executed.
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