In this article, we will learn about the if else elif statement in python that is used for decision making in Python programming.
What is if…else statement in Python?
When we want to use conditional logic, we use if else statement for executing the code when a certain condition is fulfilled.
The if…elif…else statement is used in Python for decision making.
Python if Statement Syntax
if condition: statement(s)
Here, the Python program evaluates the condition. The program will execute statement(s) only if the condition is True.
The Python program will not execute statement(s), If the condition is False .
The body of the if statement is indicated by the indentation.
All non-zero values are intepreted as True. None and 0 are interpreted as False.
Example: Python if Statement
x= 20 if (x > 25): print ("20 is less than 25") print ("This is not if")
Output
This is not if
Python if…else Statement
Syntax of if…else
if test condition: Body of if else: Body of else
The if..else statement evaluates the test condition and will execute the body of if only when the test condition is True.
If the condition is False, the body of else is executed. Indentation is used to separate the blocks.
Example of if…else
x= 25; if (x < 10): print ("x is smaller than 10") else: print ("x is greater than 10")
Output
x is greater than 10
Python if…elif…else Statement
Syntax of if…elif…else
if test condition: Body of if elif test condition: Body of elif else: Body of else
- 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.
- Only one block among the several if…elif…else blocks is executed according to the condition.
- The if block can have only one else block. But it can have multiple elif blocks.
x = 25 if (x == 15): print ("x is 15") elif (x == 12): print ("x is 12") elif (x == 25): print ("x is 25") else: print ("x is not present")
Output
x is 25
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
x = 234 y = 32 if x > y: print("x is greater than y")
Output
x is greater than y
Python Nested if statements
You can have if statements inside if statements, this is called nested if statements.
Example
a = 60 if a > 10: print("Greater ten") if a > 30: print("and also greater 30") else: print("but not greater 30")
Output
Greater ten and also greater 30!