Conditional Statement
In Python, a conditional statement or block refers to a section of code that is executed only if a certain condition is met. The most common conditional statements in Python are:
- simple if
- if…else
- elif
- nested if
1. Simple if Example:
It allows you to execute a block of code if a specified condition is true.
x = 10 if x > 5: print("x is greater than 5") """ Output: x is greater than 5 """
2. if else Example:
It allows you to execute one block of code if the condition is true, and another block if it’s false.
x = 3 if x % 2 == 0: print("x is even") else: print("x is odd") """ Output: x is odd """
3. elif Example:
It stands for “else if” and allows you to check for multiple conditions after an initial if statement.
age = 20 if age < 18: print("You are a minor") elif age >= 18 and age < 65: print("You are an adult") else: print("You are a senior citizen")
4. Short Hand If:
If you have only one statement to execute, you can put it on the same line as the if statement.
a = 200 b = 33 if a > b: print("a is greater than b") #Output: a is greater than b
5. Short Hand If … Else:
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line
a = 2 b = 330 print("A") if a > b else print("B") #Output: B
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
a = 33 b = 200 if b > a: pass