All 1.4 24 min read 10 question quiz 21 exam marks

Selection: if, elif and else

Making a program choose. Conditions, elif chains, boolean logic, and the ordering mistake that quietly gives everybody the same answer.

Making a decision

Everything so far has run top to bottom, every line, every time. Selection is how a program takes one path instead of another.

Python
age = int(input("How old are you? "))

if age >= 18:
    print("You may vote.")
else:
    print("Not yet.")

The three rules

  1. A colon at the end of every if, elif and else line
  2. The block underneath is indented, four spaces, and the indentation is what decides

which lines belong to the branch

  1. Conditions are checked top to bottom, and the first true one runs while every

other branch is skipped

Python
mark = int(input("Enter the mark: "))

if mark >= 70:
    print("Distinction")
elif mark >= 50:
    print("Merit")
elif mark >= 40:
    print("Pass")
else:
    print("Fail")
Order conditions from most restrictive to least

If mark >= 40 came first, a mark of 95 would print "Pass" and never reach the distinction branch, because Python stops at the first true condition. The program does not crash. It just quietly gives the wrong answer.

if, elif and else are one statement

A common misunderstanding is that these are three separate statements. They are one.

Python
# One decision, three possible outcomes. Exactly one branch runs.
if temperature > 25:
    print("Hot")
elif temperature > 15:
    print("Mild")
else:
    print("Cold")

# Three separate decisions. Several can run.
if temperature > 25:
    print("Hot")
if temperature > 15:
    print("Mild")
if temperature > 5:
    print("Not freezing")

With temperature = 30 the first version prints only "Hot". The second prints all three lines, because each if is judged independently.

= assigns, == compares

if score = 10: is a syntax error. One equals sign means "make this the value". Two means "are these equal?". Python refuses the first inside a condition precisely because the mistake used to be so costly in other languages.

if, elif and else: the first true branch winsA grading program with the score 65, and the route that 65 takes. The first test, score greater than or equal to 70, is False, so the block that prints A is skipped. The second test, score greater than or equal to 60, is True, so its block runs and prints B. Because a branch has been chosen, the else is never reached. Only one branch of an if, elif and else ever runs, and it is the first one whose condition is True. That is why the order of the tests matters: if a test for 50 or more had been written first, a score of 90 would satisfy it and receive the lowest grade, so the strictest condition must come first.grade.py1score = 652if score >= 70:3    print("A")4elif score >= 60:5    print("B")6else:7    print("C")Where does 65 go?65score >= 70Falseskip "A"score >= 60Trueprints "B"elsenever reachedfirst True branch winsOrder mattersTest the strictest condition first.if score >= 50:   # catches 90 too!    print("C")a 90 would get the C: the first test is True1234
  1. The code: if, elif and else test one condition after another.
  2. Follow the value 65 down: each test is True or False, in order.
  3. The first True test runs its block, and the rest are skipped.
  4. So test the strictest condition first, or an easy one will catch everything.
Conditions are checked in order, and checking stops at the first one that is True.

Boolean logic

A condition is any expression that evaluates to True or False.

OperatorMeaningTrue when
==equal to5 == 5
!=not equal to5 != 3
>greater than7 > 3
<less than3 < 7
>=greater than or equal5 >= 5
<=less than or equal5 <= 5

Combining conditions

Python
age = 16
has_permission = True

if age >= 18 or has_permission:
    print("Allowed in")

if age >= 13 and age <= 19:
    print("Teenager")

if not has_permission:
    print("Permission needed")
  • and is true only when both sides are true
  • or is true when at least one side is true
  • not reverses a condition

Chaining comparisons

Python lets you write a range the way maths does, and it is clearer:

Python
if 13 <= age <= 19:        # same as age >= 13 and age <= 19
    print("Teenager")

Checking membership

Python
command = input("> ").lower()

if command in ["quit", "exit", "q"]:
    print("Goodbye")

if "a" in "banana":
    print("Found one")

in saves you writing the same comparison three times with or between them.

Watch the boundary

Most selection bugs sit on exactly the boundary value. If a condition mentions 40, test 39, 40 and 41. > and >= behave identically everywhere except at the one value that matters.

Patterns that keep selection readable

Nested selection

An if inside another if. The inner one is only reached when the outer condition is true.

Python
if logged_in:
    if is_admin:
        print("Admin dashboard")
    else:
        print("User dashboard")
else:
    print("Please log in")

Combining rather than nesting

The same logic, one level flatter, and usually easier to follow:

Python
if logged_in and is_admin:
    print("Admin dashboard")
elif logged_in:
    print("User dashboard")
else:
    print("Please log in")
Flatten where you can

Deep nesting is the single biggest cause of unreadable beginner code. If you are three levels in, ask whether and or an early exit would say the same thing in one level.

Validating before you act

Python
reply = input("Enter your age: ")

if not reply.isdigit():
    print("That is not a whole number.")
else:
    age = int(reply)
    if age >= 18:
        print("You may vote.")
    else:
        print("Not yet.")

Checking the input first means int() is only ever handed something it can convert, so the program explains the problem instead of crashing.

match, for many fixed options

Python
command = input("Enter a command: ").lower()

match command:
    case "go":
        print("You move forward.")
    case "look":
        print("You see a door.")
    case "quit":
        print("Goodbye.")
    case _:
        print("I do not understand.")

match compares one value against a list of fixed possibilities. The underscore case runs when nothing else matched, exactly like else. A long elif chain that keeps testing the same variable is usually clearer written this way.

The same grading code written as nested ifs and as a flat if, elif, else chainThe same grading code written two ways. Nested ifs go three levels deep, checking mark is at least 0, then at most 100, then at least 70, and the word invalid appears twice, so the code is hard to follow. The flat version checks the bad cases first, if mark is below 0 or above 100 then the grade is invalid, then elif mark is at least 70 the grade is A, else the grade is B. It is one level deep, every case is in the open and only one branch ever runs. Both give the same answers: a mark of 85 is A, 55 is B and 120 is invalid.Nested: hard to follow1if mark >= 0:    if mark <= 100:        if mark >= 70:            grade = "A"        else:            grade = "B"    else:        grade = "invalid"else:    grade = "invalid"three levels deep, and invalid appears twiceFlat: check the bad cases first2if mark < 0 or mark > 100:    grade = "invalid"elif mark >= 70:    grade = "A"else:    grade = "B"one level, and every case is in the openGuard firstdeal with the invalid values straight awayelif chainonly one branch ever runsThe same answer, in a shape you can read3mark = 85Amark = 55Bmark = 120invalid
  1. Nested ifs push the code to the right and repeat cases.
  2. A flat chain checks the invalid values first and then the normal cases. Only one branch runs.
  3. Both give the same answers, but the flat one is easier to read and to test.
Flatten selection: guard against bad values first, then use elif for the normal cases.

Key terms you must be able to define

Selection
Choosing between different paths through a program depending on a condition.
Condition
An expression that evaluates to either True or False.
if
Starts a selection statement, running its block only when the condition is true.
elif
Short for else if. Tests another condition, but only if every condition above it was false.
else
Runs when no condition above it was true. It takes no condition of its own.
Boolean operator
and, or and not, used to combine or reverse conditions.
Nested selection
An if statement placed inside the block of another if statement.
Boundary value
The exact value at which a condition changes from false to true.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineSelection
AnswerChoosing between different paths through a program depending on a condition.
DefineCondition
AnswerAn expression that evaluates to either True or False.
Defineif
AnswerStarts a selection statement, running its block only when the condition is true.
Defineelif
AnswerShort for else if. Tests another condition, but only if every condition above it was false.
Defineelse
AnswerRuns when no condition above it was true. It takes no condition of its own.
DefineBoolean operator
Answerand, or and not, used to combine or reverse conditions.
DefineNested selection
AnswerAn if statement placed inside the block of another if statement.
DefineBoundary value
AnswerThe exact value at which a condition changes from false to true.

Reach the top grade on this topic

  • Order elif conditions from most restrictive to least, and explain why it matters
  • Choose between > and >= deliberately by testing the boundary value itself
  • Combine conditions with and and or instead of nesting three levels deep
  • Explain why an elif chain gives one outcome while separate ifs can give several
  • Validate input before converting it, so the program reports the problem rather than crashing

Mistakes that cost marks here

Avoid these
  • Using a single equals sign in a condition, which is a syntax error.
  • Ordering elif branches from least restrictive to most, so every value matches the first branch.
  • Forgetting the colon at the end of the if line.
  • Writing several separate ifs where one elif chain was meant, so more than one branch runs.
  • Using > where >= was needed, which fails at exactly the boundary value.
  • Writing if age >= 13 and <= 19, which is not valid. Each side of and must be a complete condition.
Fun fact

Python checks an elif chain from the top and stops at the first true condition. That is why a grade boundary program with the conditions in the wrong order does not crash, it just silently gives every student the same grade, which is far harder to spot.

Knowledge check

0 of 10 answered
1What is wrong with if score = 10:?
2A program has if mark >= 40 before elif mark >= 70. What does a mark of 90 print?
3When is age >= 13 and age <= 19 true?
4What does not True evaluate to?
5With temperature = 30, how many lines does three separate if statements print, if all three conditions are true?
6What does else take as its condition?
7Which is equivalent to age >= 13 and age <= 19?
8What decides which lines belong inside an if branch?
9In a match statement, what does case _: do?
10A condition uses if mark > 40 for a pass. What happens to a mark of exactly 40?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

21 marks
1Write a program that asks for a mark out of 100 and prints Distinction for 70 or above, Merit for 50 to 69, Pass for 40 to 49 and Fail below 40.5 marks
Write

Mark scheme0 / 5
  • LReads and converts the input
  • LTests for 70 or above first
  • LUses elif for the 50 boundary
  • LUses elif for the 40 boundary
  • LUses else for everything below 40
Model answer

mark = int(input("Enter the mark: ")) if mark >= 70: print("Distinction") elif mark >= 50: print("Merit") elif mark >= 40: print("Pass") else: print("Fail") The conditions are ordered from most restrictive to least, which is essential. Python checks each condition in turn and runs the first one that is true, skipping the rest, so a mark of 85 is correctly caught by the first branch. If the 40 test came first, every mark of 40 or above would print Pass and the higher grades would never be reached.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain the difference between using an elif chain and using several separate if statements.4 marks
Explain

Mark scheme0 / 4
  • LAn elif chain is a single statement
  • LOnly the first true branch runs and the rest are skipped
  • LSeparate ifs are each judged independently
  • LSo several separate ifs may all run
Model answer

An if, elif and else chain forms one single selection statement with several possible outcomes. Python tests each condition from the top and runs the block belonging to the first one that is true, then skips every remaining branch entirely, so exactly one branch runs. Several separate if statements are instead judged one after another and completely independently of each other, so if more than one of their conditions happens to be true then more than one block will run. This is why a temperature of 30 prints only Hot from an elif chain, but would print Hot, Mild and Not freezing from three separate ifs.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3A program checks exam marks using if mark >= 40 followed by elif mark >= 70. Explain why no student is ever awarded a distinction, and state the correction.4 marks
Explain

Mark scheme0 / 4
  • LPython checks conditions from the top and stops at the first true one
  • LAny mark of 70 or more also satisfies the 40 condition
  • LSo the 40 branch always runs first and the elif is never reached
  • LReorder so the most restrictive condition is tested first
Model answer

Python evaluates the conditions of a selection statement in the order they are written and runs the block belonging to the first condition that is true, skipping all the others. A mark of 85 satisfies mark >= 40 just as much as it satisfies mark >= 70, so the first branch is taken and the elif below it is never even tested. Every student scoring 40 or above therefore receives the same message. The correction is to order the conditions from most restrictive to least, testing mark >= 70 first, then mark >= 50, then mark >= 40, so that each mark is caught by the highest band it qualifies for.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Write a program that asks the user for their age, checks that what they typed is a whole number, and then states whether they may vote at 18 or not.5 marks
Write

Mark scheme0 / 5
  • LReads the input as a string first
  • LChecks the input is numeric before converting
  • LReports the problem if it is not numeric
  • LConverts the valid input to an integer
  • LUses selection to print the correct voting message
Model answer

reply = input("Enter your age: ") if not reply.isdigit(): print("That is not a whole number.") else: age = int(reply) if age >= 18: print("You may vote.") else: print("Not yet.") The input is read as a string and checked with isdigit before any conversion is attempted, so int is only ever given something it can actually convert. Without that check, typing a word would raise a ValueError and stop the program. Validating first means the program explains the problem to the user instead of crashing, which is what any real program is expected to do.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain why combining two conditions with and is often preferable to nesting one if statement inside another.3 marks
Explain

Mark scheme0 / 3
  • LNesting adds a level of indentation for each condition
  • LDeeply nested code is harder to read and follow
  • LA single condition joined with and expresses the same logic in one level
Model answer

Each nested if adds another level of indentation, and code that is three or four levels deep becomes genuinely difficult to read because the reader has to hold every enclosing condition in their head at once to know when a line will actually run. Joining the conditions with and expresses exactly the same requirement, that both must be true, while keeping the code at a single level of indentation. The nested form is only preferable when the two conditions need separate else branches, because then each if genuinely has its own alternative to handle.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 21