Control Flow - If/Elif/Else
Python Programming
Control Flow - If/Elif/Else
Control flow statements allow your programs to make decisions and execute different blocks of code based on conditions. The if/elif/else construct is the most fundamental control flow mechanism in Python. Unlike many other languages that use curly braces to define code blocks, Python uses indentation. This enforced indentation makes Python code inherently readable and consistent across different codebases and development teams.
Basic If Statements
age = 18
# Simple if
if age >= 18:
print("You are an adult.")
# If-else
temperature = 35
if temperature > 30:
print("It's hot outside!")
else:
print("The weather is pleasant.")
# If-elif-else (multiple conditions)
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade: {grade}") # "Your grade: B"
Nested Conditions and Complex Logic
# Nested if statements
age = 25
has_license = True
if age >= 16:
if has_license:
print("You can drive.")
else:
print("You need a license first.")
else:
print("You are too young to drive.")
# Better: flatten with 'and'
if age >= 16 and has_license:
print("You can drive.")
elif age >= 16:
print("You need a license first.")
else:
print("You are too young to drive.")
# Complex conditions with parentheses for clarity
user_role = "admin"
is_active = True
has_2fa = True
if (user_role == "admin" or user_role == "moderator") and is_active:
if user_role == "admin" and not has_2fa:
print("Admin accounts require 2FA.")
else:
print("Access granted.")
else:
print("Access denied.")
Ternary (Conditional) Expression
Python supports a one-line conditional expression that is useful for simple conditions. It follows the pattern: value_if_true if condition else value_if_false.
# Ternary expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # "adult"
# Useful in function calls
print("Even" if 10 % 2 == 0 else "Odd")
# Nested ternary (avoid — hard to read)
x = 15
label = "low" if x < 10 else "medium" if x < 20 else "high"
# Better: use regular if/elif/else for complex logic
if x < 10:
label = "low"
elif x < 20:
label = "medium"
else:
label = "high"
Truthy and Falsy Values
Python evaluates certain values as False in a boolean context (falsy) and everything else as True (truthy). Understanding this lets you write cleaner conditions.
# Falsy values: False, 0, 0.0, "", [], {}, set(), None
# Everything else is truthy
# Instead of:
if len(my_list) > 0:
print("List has items")
# Write:
my_list = [1, 2, 3]
if my_list:
print("List has items")
# Instead of:
if name != "":
print(f"Hello, {name}")
# Write:
name = "Alice"
if name:
print(f"Hello, {name}")
# Checking for None
result = None
if result is None:
print("No result yet")
# Guard clause pattern (early return)
def process_order(order):
if not order:
print("No order provided")
return
if not order.get("items"):
print("Order has no items")
return
# Main logic here
total = sum(item["price"] for item in order["items"])
print(f"Order total: ${total:.2f}")
process_order({"items": [{"price": 9.99}, {"price": 14.99}]})
Match Statement (Python 3.10+)
# Structural pattern matching (like switch/case but more powerful)
def handle_command(command):
match command.split():
case ["quit"]:
print("Goodbye!")
case ["hello", name]:
print(f"Hello, {name}!")
case ["add", *numbers]:
total = sum(int(n) for n in numbers)
print(f"Sum: {total}")
case _:
print(f"Unknown command: {command}")
handle_command("hello Alice") # "Hello, Alice!"
handle_command("add 1 2 3 4") # "Sum: 10"
handle_command("quit") # "Goodbye!"
Pro tip: Use guard clauses (early returns) to reduce nesting. Instead of wrapping your entire function in an if-else block, check for error conditions first and return early, keeping the main logic at the top level of indentation.
Key Takeaways
- Python uses
if,elif, andelsefor conditional execution, with indentation defining code blocks. - The ternary expression
x if condition else yprovides a concise one-line conditional. - Understanding truthy/falsy values lets you write cleaner conditions: empty collections, zero, empty strings, and None are all falsy.
- Use guard clauses (early returns) to reduce nesting and improve readability.
- Python 3.10+ introduces
match/casefor powerful structural pattern matching.