Python if...else Statement
1. Basic if Statement
age = 20
if age >= 18:
print("Eligible to vote")Executes the block only when the condition evaluates to True.
2. Using if...else Statement
temperature = 15
if temperature > 25:
print("It's warm outside")
else:
print("It's cold outside")Provides an alternative execution path when the condition is False.
3. Using if...elif...else Chain
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: D")Allows testing multiple conditions in sequence.
4. Nested if Statements
An if block can exist inside another for complex logic.
5. Using Logical Operators in Conditions
Combine multiple conditions using and, or, and not.
6. Short-Hand if Statement (Single Line)
Useful for minimal conditional checks.
7. Short-Hand if...else (Ternary Expression)
Compact inline conditional assignment.
8. Checking Multiple Values with in
Efficient alternative to chained OR conditions.
9. Comparing Strings in Conditions
Common technique to handle case-insensitive comparisons.
10. Using pass in if Statement
pass acts as a syntactic placeholder to avoid errors for empty blocks.
Last updated