if / elif / else & logical operators
Branch on conditions and combine them with and / or / not.
Why branching is the core of every program
Software makes decisions. A login route checks whether a token is valid, an ETL job sends a row to "clean" or "quarantine", a pricing function picks a tier. All of that is if/elif/else. Getting the branch order and the boolean logic right is the difference between code that handles every case and code that silently mishandles one.
The mental model: first true branch wins
Python evaluates the conditions top to bottom and runs the block under the first one that is True. Every later branch is skipped, even if it would also be true. else is the catch-all that runs when nothing above it matched.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("F") # prints B
score is 85, so score >= 90 is False, score >= 80 is True, and Python stops there and prints B. Order matters. If you had checked score >= 80 first, a 95 would also match it and wrongly print B. Put the tightest condition first.
Comparisons produce booleans
Each comparison evaluates to True or False:
| You type | It means | A true example |
|---|---|---|
| == | equal to | 3 == 3 |
| != | not equal to (≠) | 3 != 4 |
| < | less than | 2 < 3 |
| > | greater than | 4 > 3 |
| <= | at most (≤) | 3 <= 3 |
| >= | at least (≥) | 3 >= 3 |
Use == to compare and a single = to assign. Swapping them is a classic bug. Python also allows chained comparisons, so 0 < x < 10 means "x is between 0 and 10" and reads exactly like math.
Combining conditions with and / or / not
age >= 18 and citizen # True only if both are True
is_weekend or is_holiday # True if at least one is True
not finished # flips the boolean
That first line is the shape of the can_vote exercise: return age >= 18 and citizen. For sign(n) you branch on three ranges. Check n > 0, then elif n < 0, then else for "zero". Because the first true branch wins, else safely means "exactly 0" without you re-testing it.
Pitfall: truthiness and short-circuiting
if, and, and or do not require real booleans. Python treats 0, 0.0, "", [], {}, and None as falsy and nearly everything else as truthy, so if items: means "if the list is non-empty". Watch the trap: writing if age == 18 when you meant age >= 18 rejects everyone older. And and/or short-circuit, stopping as soon as the answer is known, which is why user and user.name never crashes on a None user.
Interview nuance: and and or return one of their operands, not a coerced True/False. x and y gives x when x is falsy, otherwise y. x or y gives x when x is truthy, otherwise y. So "" or "guest" returns "guest" (a common default-value trick) and 3 and 5 returns 5. In age >= 18 and citizen, both operands are booleans (age >= 18 is a comparison result and citizen is True or False), so the expression evaluates to a clean True/False, which is exactly what can_vote should return.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("F") # prints BApply
Your turn
The task this lesson builds to.
Implement sign(n): return "positive" when n is greater than 0, "negative" when it's
less than 0, and "zero" when it's exactly 0.
3 hints and 4 automated checks are waiting in the workspace.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Implement can_vote(age, citizen): return True only when age is at least 18 and
citizen is True.
2 hints and 4 automated checks are waiting in the workspace.