How do conditionals (if/elif/else) work in Python?
· Category: Python Programming
Short answer
Python uses if, elif, and else to execute blocks of code conditionally. Indentation defines the block scope. Conditions evaluate to truthy or falsy values.
Steps
- Start with
if condition:. - Add optional
elif another_condition:blocks. - End with an optional
else:catch-all block.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}")
Tips
- Truthy values: non-zero numbers, non-empty sequences,
True. Falsy:0,0.0,None, empty collections,False. - Use
and,or, andnotto combine conditions. - Python supports inline ternary expressions:
value = a if condition else b. match/case(structural pattern matching) is available in Python 3.10+ for complex branching.
# Ternary
status = "active" if score > 0 else "inactive"
# match/case (Python 3.10+)
match grade:
case "A":
print("Excellent")
case "B" | "C":
print("Good")
case _:
print("Needs improvement")
Common issues
- Forgetting the colon
:at the end of the condition line causes aSyntaxError. - Using assignment
=instead of comparison==inside a condition is a common typo. - Incorrect indentation changes which statements belong to which block.