Topic 11 of 58
if / else
Overview
Control flow statements dictate the path a program takes based on dynamic conditions. Python uses if, elif (short for else if), and else to construct these decision trees. Python evaluates the conditions sequentially from top to bottom; the first condition that evaluates to True executes its indented block, and the rest of the chain is completely bypassed.
Syntax
python
temperature = 22
if temperature > 30:
print("It's scorching hot.")
elif temperature > 20:
print("It's a pleasant day.")
elif temperature > 10:
print("It's a bit chilly.")
else:
print("It's freezing!")
# Ternary Operator (Conditional Expression for one-liners)
# Syntax: value_if_true if condition else value_if_false
weather = "Good" if temperature > 20 else "Bad"
print(weather) # Output: "Good"Common Pitfalls
- Forgetting the colon
:at the end of the condition line. - Misaligning the indentation for
eliforelse, causing syntax errors. - Checking conditions out of logical order (e.g., checking
> 20before checking> 30), which intercepts the flow prematurely.
Interview Questions
Q:
Does Python have a
switch or case statement?A:
Historically, no. Developers had to use long if/elif chains or dictionary mapping. However, Python 3.10 introduced the match/case statement for advanced structural pattern matching.
Real-World Example
Evaluating truthy/falsy values cleanly without explicit comparisons.
example
python
users = []
# Instead of checking 'if len(users) == 0:', Pythonic code relies on falsy evaluation.
# Empty lists, empty strings, 0, and None all evaluate to False natively.
if not users:
print("The user database is completely empty.")
else:
print(f"Found {len(users)} users.")Check Your Knowledge
Test your understanding of if / else with these quick questions.