1.2Conditions (if / elif / else)
The essentials in 30 seconds
- The test decides, indentation delimits: block indented with 4 spaces after the : — no braces, never mix spaces/tabs.
- elif = the ladder: tested in order, stopping at the first true one — order from most specific to most general, else catches the rest.
- Readable conditions: chained comparisons (18 <= age < 65), in for membership, falsy values (None, 0, "", []) tested directly.
Running mini-case — Nabil classifies respondents in Algiers
Nabil must classify his survey respondents by group: child, teenager, adult, senior — with an associated workshop fee. He first writes a cascade of independent ifs with mixed indentation: IndentationError, then a 26-year-old respondent validated in two groups. He fixes it with an if/elif/else ordered from most specific to most general, 4 spaces everywhere, and a readable test 18 <= age < 65: each respondent falls into exactly one group.
Continuation of case 1.1 — Nabil moves from storing data to decisions.
1. The test decides, indentation delimits
A condition directs the program: if age >= 18: then a block indented with 4 spaces — indentation is the structure (no braces, no end). elif (else if) tests another condition if the previous one is false; else covers all other cases. Python evaluates in order and stops at the first true block: order from most specific to most general.
Nabil converts his entered age to int then writes if/elif/else by groups: the 26-year-old respondent is no longer counted twice, and VS Code converts his tabs to spaces.
2. Conditions that read well
Python writes tests as you read them: chained comparisons (if 18 <= age < 65:), in for membership (if user in admitted:), and/or/not logic with short-circuiting. "Falsy" values: None, 0, "", [], {} — if my_list: is enough to test emptiness. Ten nested ifs signal a design problem (function, dictionary).
Nabil replaces his double comparisons with 18 <= age < 65 and tests his respondent list with if respondents:: the code reads like the business rule.
🔎 Concrete example — 🔎 Concrete example — A fee that reads like the rule
Ordered groups, like Nabil for his workshops.
age = 26
if age < 12:
tarif = 0
elif age < 26:
tarif = 5
elif age < 65:
tarif = 10
else:
tarif = 7
print(f"Age {age}: fee {tarif}")
print(18 <= age < 65) # True: chained comparison
Reading: each group tested once, in order — the final else catches those left out.
Lesson: the chained comparison 18 <= age < 65 reads like the business rule.
Section vocabulary
- if / elif / else
- if tests a condition; elif tests another one if the previous is false; else covers all other cases. Evaluation in order, stopping at the first true one.
Simple example: The age groups classified by Nabil.
What it is not: three independent ifs that validate the same case twice.
Reflex: one ordered ladder, specific first, else at the end.
- Indentation
- Offset at the start of a line (4 spaces by convention) defining which block an instruction belongs to. Mandatory in Python, not decorative.
Simple example: The group blocks indented by Nabil.
What it is not: mixing spaces/tabs in the same file.
Reflex: 4 spaces, strict consistency, VS Code as converter.
- Comparison operators
- ==, !=, <, >, <=, >=: compare two values and return a boolean. Python allows chained comparisons: 18 <= age < 65.
Simple example: The 18 <= age < 65 qualifying Nabil's adults.
What it is not: = in a test (assignment, not comparison).
Reflex: == compares, = assigns; chain when readable.
- Logical operators
- and, or, not: combine several conditions, with short-circuiting (stopping as soon as the result is known).
Simple example: Nabil's age >= 18 and licence for the driving workshop.
What it is not: stacking ten nested ifs instead of combining.
Reflex: combine with and/or/not rather than nesting.
- Boolean expression
- Any expression evaluating to True or False, evaluated by the condition. The values None, 0, "", [] are false: if my_list: is enough.
Simple example: The if respondents: checking that Nabil has data.
What it is not: explicitly comparing to True/False everywhere.
Reflex: test emptiness directly, without detour.
In practice — In practice — Writing branches with if/elif/else
- Write a program that reads an age (input converted to int) and displays "Adult" if ≥ 18, otherwise "Minor". Take care with block indentation.
- Add an intermediate case with elif: "Child" (< 12), "Teenager" (< 18), "Adult" (otherwise).
- Combine conditions: "if age >= 18 and licence == True". Test and, or and not.
- Deliberately trigger an IndentationError (shift one line), read the message, then fix it: get familiar with this error.
Script ready to say — explaining elif order (30 s)
"I ordered the groups from most specific to most general: Python stops at the first true test, so the order guarantees a case never falls into two groups. And the final else catches everything we did not plan for."
Say in code review; show the business rule next to the code.
Copy-paste template — ordered groups + readable test
age = int(input("Age? "))
if age < 12:
categorie = "Child"
elif age < 18:
categorie = "Teenager"
elif age < 65:
categorie = "Adult"
else:
categorie = "Senior"
print(f"Category: {categorie}")
if 18 <= age < 65:
print("Main workshop target")
Groups in Algiers
Like Nabil: one if/elif/else ladder per group — adding a group means inserting an elif at the right rank, without touching the others.
Readable business test
18 <= age < 65 re-reads like the rule: the chained comparison avoids the redundant and.
Membership
if code in valid for survey codes: membership replaces a string of == or ==.
Empty list or not
if respondents: is enough — no need to compare the length to zero, falsy does the job.
✓ Best practices
- Indent with 4 spaces, never mixed tabs.
- Order elifs from most specific to most general.
- Test falsy directly (if list:) and chain comparisons.
✗ Common pitfalls
- Mixing tabs and spaces (IndentationError).
- Writing = instead of == in the test.
- Stacking ten nested ifs instead of rethinking the structure.
Key takeaways
- if / elif / else direct the program according to conditions, evaluated in order up to the first true one.
- Indentation (4 spaces) delimits blocks: it is mandatory, not decorative.
- Comparisons: == != < > <= >= (chainable); logic: and, or, not.
- A condition evaluates a boolean expression (True/False); None, 0, "" and [] are false.
48h challenge — apply tomorrow
Take the template above: add a 4th group (an elif at the right rank), replace a double test with a chained comparison, and trigger then fix an IndentationError. Check each group locally. 20 minutes is enough.
- I classify with an ordered if/elif/else with an else catching the rest.
- My indentation is strict (4 spaces, zero mixing).
- I write readable tests (chained, in, and/or/not).
Frequently asked questions
How many spaces for indentation?
The convention (PEP 8) is 4 spaces per level. The key is consistency: never mix spaces and tabs in the same file. VS Code converts tabs to spaces automatically — enable showing whitespace to check.
Can you chain several elifs?
Yes, as many as needed. Python evaluates conditions top to bottom and executes the first block whose condition is true, then exits the structure. The final else (optional) catches all remaining cases — plan for it to cover oversights.
What happens if you mix spaces and tabs?