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.
age = int(input("How old are you? "))
if age >= 18:
print("You may vote.")
else:
print("Not yet.")The three rules
- A colon at the end of every
if,elifandelseline - The block underneath is indented, four spaces, and the indentation is what decides
which lines belong to the branch
- Conditions are checked top to bottom, and the first true one runs while every
other branch is skipped
mark = int(input("Enter the mark: "))
if mark >= 70:
print("Distinction")
elif mark >= 50:
print("Merit")
elif mark >= 40:
print("Pass")
else:
print("Fail")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.
# 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, == comparesif 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.
- The code: if, elif and else test one condition after another.
- Follow the value 65 down: each test is True or False, in order.
- The first True test runs its block, and the rest are skipped.
- So test the strictest condition first, or an easy one will catch everything.
Boolean logic
A condition is any expression that evaluates to True or False.
| Operator | Meaning | True when |
|---|---|---|
== | equal to | 5 == 5 |
!= | not equal to | 5 != 3 |
> | greater than | 7 > 3 |
< | less than | 3 < 7 |
>= | greater than or equal | 5 >= 5 |
<= | less than or equal | 5 <= 5 |
Combining conditions
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")andis true only when both sides are trueoris true when at least one side is truenotreverses a condition
Chaining comparisons
Python lets you write a range the way maths does, and it is clearer:
if 13 <= age <= 19: # same as age >= 13 and age <= 19
print("Teenager")Checking membership
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.
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.
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:
if logged_in and is_admin:
print("Admin dashboard")
elif logged_in:
print("User dashboard")
else:
print("Please log in")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
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
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.
- Nested ifs push the code to the right and repeat cases.
- A flat chain checks the invalid values first and then the normal cases. Only one branch runs.
- Both give the same answers, but the flat one is easier to read and to test.
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.
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
andandorinstead 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
- 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 ofandmust be a complete condition.
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
if score = 10:?if mark >= 40 before elif mark >= 70. What does a mark of 90 print?age >= 13 and age <= 19 true?not True evaluate to?temperature = 30, how many lines does three separate if statements print, if all three conditions are true?else take as its condition?age >= 13 and age <= 19?case _: do?if mark > 40 for a pass. What happens to a mark of exactly 40?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.
- 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
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.
- 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
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.
if mark >= 40 followed by elif mark >= 70. Explain why no student is ever awarded a distinction, and state the correction.4 marks- 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
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.
- 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
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.
and is often preferable to nesting one if statement inside another.3 marks- 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
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.