Skip to content
Study Hall
Lesson 2 of 5Computer Programming
Unit 5 · Lesson 2 of 5

Selection: if, elif and else

How a program makes a decision, and how to write conditions that are actually correct at their boundaries.

4 min read9 practice questionsAsk AI about this →

Key things to remember

  1. 1if tests a condition; elif is checked only when everything above was False; else catches everything remaining.
  2. 2In Python, indentation defines the block — it is syntax, not formatting.
  3. 3and needs both conditions true; or needs at least one.
  4. 4"Outside a range" uses or; "inside a range" uses and.
  5. 5An if-elif chain runs at most one branch; separate ifs can all run.
  6. 6Order an if-elif chain from the most specific condition to the least.
  7. 7Test at the boundary, one below and one above.

Without selection a program can only do exactly one thing. Selection lets it choose a path based on a condition — a test that evaluates to True or False. That single capability is what separates a program from a calculator, and it is the point at which programs start being able to be wrong in interesting ways.

PythonWhat it does
if mark >= 50:Tests the condition; runs the indented block if True
print("Pass")The indented body — runs only when the condition holds
elif mark >= 40:Checked ONLY if every condition above was False
print("Borderline")Body of the elif
else:Runs when no condition above was True. No condition of its own
print("Fail")Body of the else
Indentation is the syntax
Most languages mark a block with braces. Python uses indentation, which means the indentation IS the program structure, not decoration. A line indented under an if runs only when the condition is true; a line at the outer level always runs. Mixing tabs and spaces produces confusing errors, so let your editor insert four spaces.
The first true condition wins — everything below it is skipped.mark >= 80trueLevel 4falsemark >= 70trueLevel 3falsemark >= 60trueLevel 2falseelse: Level 1all paths rejoin hereOrder the tests from the highest threshold down, or an 85 matches "mark >= 60" first.
Fig 1An if-elif-else chain: the first true condition wins and the rest never run.

Comparison and logical operators

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
< >Less / greater than3 > 7False
<= >=Less / greater than or equal5 >= 5True
andBoth conditions must be Truex > 0 and x < 10True only inside the range
orAt least one must be Trueday == "Sat" or day == "Sun"True on either day
notReverses a conditionnot (x > 5)True when x ≤ 5
The and/or mistake
To test whether a value is outside the range 0 to 100, you need x < 0 or x > 100. Writing and there gives a condition that can never be true — no number is both below 0 and above 100. Read the condition aloud: "less than zero AND greater than a hundred" is obviously impossible, and hearing it is faster than debugging it.

Order matters in an if-elif chain

Python checks the branches in order and stops at the first one that is True. That makes ordering part of the logic, not a style choice. Testing mark >= 50 before mark >= 80 means an 85 matches the first branch and never reaches the second — so every strong student is reported as a bare pass. Write the chain from the most specific condition to the least, which for numeric ranges means from the highest threshold down.

Correct orderWhy
if mark >= 80: # Level 4Highest threshold first, so 85 is caught here
elif mark >= 70: # Level 3Only reached when the mark is below 80
elif mark >= 60: # Level 2Only reached when below 70
elif mark >= 50: # Level 1Only reached when below 60
else: # Below 50Everything remaining
elif versus a stack of ifs
Separate if statements are all evaluated, so several branches can run. An if-elif chain runs at most one branch. When the cases are mutually exclusive — a mark is exactly one level — use elif: it is faster, and more importantly it makes the exclusivity explicit so a later reader cannot get it wrong.

Boundaries are where bugs live

Almost every selection bug is an off-by-one at a boundary. > and >= differ on exactly one value, and that value is usually the one that matters — the pass mark, the maximum, the zero case. When you test a program, do not test the middle of each range. Test exactly on the boundary, one below it, and one above it. A test with a mark of 50, 49 and 51 finds bugs that a test with 75 never will.

ANested if
  • An if inside another if's body
  • Use when the second test only makes sense if the first passed
  • if logged_in: then if is_admin:
  • Gets unreadable past two or three levels
BCombined condition
  • One if with and
  • Use when the tests are independent
  • if logged_in and is_admin:
  • Flatter and usually easier to read

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Write a program that reads a mark out of 100 and prints the Ontario achievement level: Level 4 for 80+, Level 3 for 70–79, Level 2 for 60–69, Level 1 for 50–59, and below Level 1 under 50.
Example 2
A validation check should reject any mark below 0 or above 100. A student writes if mark < 0 and mark > 100: and finds nothing is ever rejected. Explain and fix.
Example 3
Trace this code with temp = 25: if temp > 30: print "Hot"; elif temp > 20: print "Warm"; elif temp > 10: print "Mild"; else: print "Cold". What is printed, and what would print with temp = 35?

Where marks get lost

  • Using = instead of == in a condition.
  • Using and when testing whether a value is outside a range — it should be or.
  • Ordering an if-elif chain from the lowest threshold up, so high values match an early branch.
  • Forgetting the colon at the end of an if, elif or else line.
  • Inconsistent indentation, which either raises an error or silently moves a line out of the block.
  • Putting a condition on else. It takes no condition; use elif if you need one.
  • Testing only the middle of each range and never the boundary value itself.

Flashcards 8

When is an elif branch checked?
How many branches of an if-elif-else chain can run?
How do you test whether x is inside the range 0 to 100?
How do you test whether x is outside the range 0 to 100?
+ 4 more

Practice

1
How many branches of an if-elif-elif-else chain can execute in one pass?
2
Which condition correctly tests whether age is a teenager (13 to 19 inclusive)?
3
This chain is written as if m >= 50: Pass, elif m >= 80: Excellent. What does a mark of 85 print?
4
Write the condition that tests whether x is NOT equal to 10.
5
What is wrong with if mark = 50:?
6
Order these conditions correctly for a grade chain that checks marks from highest to lowest.
  1. 1elif mark >= 70:
  2. 2else:
  3. 3elif mark >= 60:
  4. 4if mark >= 80:
7
What does not (x > 5) evaluate to when x = 5?
8
Match each requirement to its condition.
x is between 1 and 10 inclusive
x is outside 1 to 10
x is exactly 7
x is anything but 7
9
A program rejects marks under 0 or over 100. Which set of test values best checks it?

Spot a mistake on this page? Let us know