Conditionals: if, elif and else
Making decisions in Python: if, else and elif chains, truthy and falsy values, combining conditions, nesting versus flat logic, and the conditional expression.
Running code only when a condition holds
So far every line of a program has run. Real programs choose: show an error only if the input is invalid, apply a discount only on Tuesdays. The if statement runs its indented block only when its condition is true.
The condition is any expression; Python evaluates it and checks whether the result is true. Comparisons (>=, ==, in, ...) produce True or False directly. The line ends with a colon, and the block below it is indented by four spaces. The first line that is not indented marks the end of the block.
1balance = 1202price = 753if balance >= price:4 balance -= price5 print("Purchased. Remaining balance:", balance)6print("Done")
Purchased. Remaining balance: 45 Done
Two paths: if and else
else adds the path to take when the condition is false. Exactly one of the two blocks runs, never both and never neither.
else has no condition of its own; it simply catches everything the if did not.
1number = 172if number % 2 == 0:3 print(number, "is even")4else:5 print(number, "is odd")
17 is odd
Many paths: elif chains
When there are more than two cases, chain them with elif ("else if"). Python tests the conditions from top to bottom and runs the block of the first one that is true; everything after it is skipped, even if it would also be true. A final else handles whatever is left.
Because the first match wins, order matters. Put the most specific or most restrictive case first. In the example, checking score >= 50 before score >= 90 would label every high score as a pass.
Each later condition can also rely on the earlier ones being false: in the elif score >= 75 branch you already know the score is below 90, so there is no need to write 75 <= score < 90.
Use one if/elif/else chain for mutually exclusive cases, and separate if statements for independent checks that may all apply.
1score = 822if score >= 90:3 grade = "Distinction"4elif score >= 75:5 grade = "Merit"6elif score >= 50:7 grade = "Pass"8else:9 grade = "Not yet"10print(score, "->", grade)
82 -> Merit
Tracing a decision
Step through this program and watch which lines run. The elif line is never evaluated: once the if condition is true, the rest of the chain is skipped.
Free shipping over 50
total = 72shipping = 10if total >= 50: shipping = 0elif total >= 25: shipping = 5final = total + shipping| Step | total | shipping | final | State Evolution |
|---|---|---|---|---|
| 1 | 72 | — | — | total is set to 72. |
Truthy and falsy values
A condition does not have to be a boolean. Python decides whether any value counts as true, its truthiness. These values are falsy:
FalseandNone- zero of any numeric type:
0,0.0 - empty collections:
"",[],(),{},set()
Everything else is truthy. That allows natural checks such as if name: (is the name non-empty?) or if not items: (is the list empty?).
Be careful when 0 is a legitimate value. If discount = 0 means "no discount", if discount: is fine; but if you are checking whether a value was provided at all, test if discount is not None: so that a real 0 is not mistaken for "missing".
1name = ""2if not name:3 name = "Guest"4print("Hello,", name)56for value in [0, 7, "", "0", None, [], [0]]:7 print(repr(value), "->", bool(value))
Hello, Guest 0 -> False 7 -> True '' -> False '0' -> True None -> False [] -> False [0] -> True
Combining conditions
Use and, or and not to build compound conditions, and parentheses when mixing them. Two more tools keep conditions short and readable:
- Chained comparisons:
if 13 <= age <= 19:instead ofif age >= 13 and age <= 19:. - Membership with
in:if day in ("Saturday", "Sunday"):instead of comparing against each value withor.
A classic bug is if day == "Saturday" or "Sunday":. Python reads it as (day == "Saturday") or "Sunday", and a non-empty string is truthy, so the condition is always true.
1age = 162day = "Sunday"3has_permission = True45if 13 <= age <= 19:6 print("Teenager")7if day in ("Saturday", "Sunday"):8 print("Weekend")9if age >= 18 or has_permission:10 print("May join the trip")11if not (age >= 18):12 print("Needs a guardian's signature")
Teenager Weekend May join the trip Needs a guardian's signature
Nested conditions and flat logic
An if can contain another if. Nesting is natural when the second question only makes sense after the first is answered, for example checking a password only after finding the user.
Deep nesting, however, quickly becomes hard to read. Two techniques flatten it:
- Combine conditions with
andwhen both must hold for a single action. - Handle the exceptional cases first, so the main case is not buried. Inside functions (next lessons) this becomes the guard clause: check what is wrong,
returnearly, and let the normal path continue unindented.
1logged_in = True2is_admin = False34# Nested: correct but grows to the right5if logged_in:6 if is_admin:7 print("Show admin panel")8 else:9 print("Show dashboard")10else:11 print("Show login page")1213# Flat: one level, same behaviour14if not logged_in:15 print("Show login page")16elif is_admin:17 print("Show admin panel")18else:19 print("Show dashboard")
Show dashboard Show dashboard
The conditional expression
When a decision only picks between two values, the conditional expression fits it on one line:
value_if_true if condition else value_if_false
It is an expression, so it can appear anywhere a value can: in an assignment, an f-string or a function argument. Keep it for simple choices; anything that needs elif or several statements belongs in a normal if block.
1items = 12label = "item" if items == 1 else "items"3print(f"You have {items} {label} in your cart.")45temperature = -36print("Freezing" if temperature < 0 else "Above zero")
You have 1 item in your cart. Freezing
Check your understanding
With `x = 15`, what does this print: `if x > 10: print("A")`, then `elif x > 5: print("B")`, then `else: print("C")`?
Practice
Four decision problems, from a single rule with exceptions to validation and grading tables.
Leap Year Check
Reveal Solution & AnalysisHide Solution
Cinema Ticket Price
Reveal Solution & AnalysisHide Solution
Triangle Classifier
Reveal Solution & AnalysisHide Solution
Grade Calculator with Edge Cases
Reveal Solution & AnalysisHide Solution
Quick Syntax & Reference Sheet
| Concept / Rule | Syntax / Usage |
|---|---|
| if / elif / else | if a:
...
elif b:
...
else:
... |
| Range check | if 0 <= x < 10: |
| Membership | if day in ("Sat", "Sun"): |
| Empty check | if not items: |
| None check | if value is None: |
| Conditional expression | label = "adult" if age >= 18 else "minor" |
Common Pitfalls & Developer Mistakes
Using = instead of == in a condition
Why it happens: if x = 5: is a SyntaxError because = is assignment.
Wrong order in an elif chain
Why it happens: A broad condition placed first catches cases meant for later branches.
Comparing against several values with or
Why it happens: x == 1 or 2 is always truthy.
Using truthiness when 0 is valid
Why it happens: if quantity: treats a real quantity of 0 like a missing value.