Python If Statements
Control Flow Focus
Python If Statements
Conditionals determine what code runs. Learn idiomatic patterns, avoid nesting hell, and keep branches maintainable.
Basic structure
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "Keep going"
Guard clauses
if not user.active:
raise PermissionError("Inactive user")
# continue with happy path
Reduces nesting and surfaces failure states early.
Nested conditionals
Use sparingly. Prefer extraction into helper functions or dictionaries:
handlers = {
"email": send_email,
"sms": send_sms,
}
handler = handlers.get(channel)
if handler:
handler(message)
else:
raise ValueError("Unsupported channel")
Ternary operator
status = "premium" if total > 100 else "standard"
Great for short expressions. Avoid chaining ternaries together; they harm readability.
Match-case vs if/elif
Use match-case when pattern matching nested structures, but stick with if/elif for simple comparisons.
Next up in your learning path
Frequently Asked Questions
Is there a switch statement in Python?
No traditional switch, but Python 3.10 introduced `match-case`, which provides pattern matching and covers most switch-style use cases.
How do I avoid deeply nested if statements?
Use guard clauses, helper functions, or dispatch tables (dict mapping keys to callables). When logic grows complex, consider state machines or strategy pattern.
Can I chain comparisons?
Yes. Python lets you write `0 < score <= 100`, which is equivalent to `(0 < score) and (score <= 100)` but more readable.