B2.3.2 Making decisions with selection
SL + HLCommand term: Construct1. Follow an if / elif / else chain
ShelfWise decides what to do about a returned book from how many days late it is. Choose a value and step through: conditions are tested top to bottom, and only the first true branch runs.
2. Condition builder: write the rule
Type a Python condition using relational operators (< <= > >= == !=) and Boolean operators (and or not). It is tested against every case, including the boundaries.
3. Truth tables
Click the result cells to set True or False, then check. Two of the expressions give identical tables: spot them (De Morgan's laws).
4. Order matters: fix the elif chain
A teammate wrote the fine bands in the wrong order. Run the test data, then move the branches (Up / Down) until every test passes.
5. Python and Java selection
Click a row to compare.
6. Flip-card deck
Click to flip. Say the answer before you flip.
7. Predict the output
Trace each snippet. Streaks of 3+ score double.
8. 45-second speed round: True or False?
A new Boolean expression each time.
if, elif and else, relational operators and Boolean operators. Watch the boundaries: they are where the tests are hardest.Expected output
Think about it
(1) Which tests in the first line check a boundary? (2) Why does menu_action need an else? (3) Write one extra test that would catch fine_owed < 2.0 written by mistake instead of <= 2.0.
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: IB grade from a percentage
Write ib_grade(percent) using if/elif/else with these (simplified) boundaries: 7 for 80+, 6 for 68+, 5 for 56+, 4 for 45+, 3 for 33+, 2 for 20+, otherwise 1. Return None for values outside 0 to 100.
Starter file (write your code where it says pass # your code here):
def ib_grade(percent):
pass # your code here
# ---- tests ----
print([ib_grade(p) for p in [95, 80, 79.9, 56, 44, 20, 3, 101, -1]])
Expected output when your code is correct:
[7, 7, 6, 5, 3, 2, 1, None, None]
Hint
Model solution
def ib_grade(percent):
if percent < 0 or percent > 100:
return None
elif percent >= 80:
return 7
elif percent >= 68:
return 6
elif percent >= 56:
return 5
elif percent >= 45:
return 4
elif percent >= 33:
return 3
elif percent >= 20:
return 2
else:
return 1
# ---- tests ----
print([ib_grade(p) for p in [95, 80, 79.9, 56, 44, 20, 3, 101, -1]])
Task 2: School trip ticket price
Ticket price: children under 5 are free; ages 5 to 17 pay 30; adults pay 60; over 65 pay 35. Members get 20% off any paid ticket. On weekends add 10 to every paid ticket (before the discount). Write price(age, member, weekend).
Starter file (write your code where it says pass # your code here):
def price(age, member, weekend):
pass # your code here
# ---- tests ----
print(price(3, True, True))
print(price(16, False, False), price(16, True, True))
print(price(40, False, True), price(70, True, False))
Expected output when your code is correct:
0 30 32.0 70 28.0
Hint
Model solution
def price(age, member, weekend):
if age < 5:
return 0
if age <= 17:
cost = 30
elif age > 65:
cost = 35
else:
cost = 60
if weekend:
cost += 10
if member:
cost *= 0.8
return round(cost, 2)
# ---- tests ----
print(price(3, True, True))
print(price(16, False, False), price(16, True, True))
print(price(40, False, True), price(70, True, False))
Task 3: Is this a real date?
Write is_leap(y) (divisible by 4, except century years, which must be divisible by 400) and is_valid_date(d, m, y) that checks the day is valid for that month. Test the edge cases 29/2/2000, 29/2/1900, 31/4/2026 and 0/1/2026.
Starter file (write your code where it says pass # your code here):
def is_leap(y):
pass # your code here
def is_valid_date(d, m, y):
pass # your code here
# ---- tests ----
for d, m, y in [(29, 2, 2000), (29, 2, 1900), (29, 2, 2024), (31, 4, 2026), (31, 12, 2026), (0, 1, 2026), (15, 13, 2026)]:
print(f"{d}/{m}/{y}: {is_valid_date(d, m, y)}")
Expected output when your code is correct:
29/2/2000: True 29/2/1900: False 29/2/2024: True 31/4/2026: False 31/12/2026: True 0/1/2026: False 15/13/2026: False
Hint
Model solution
def is_leap(y):
return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
def is_valid_date(d, m, y):
if not 1 <= m <= 12 or d < 1:
return False
if m == 2:
days = 29 if is_leap(y) else 28
elif m in (4, 6, 9, 11):
days = 30
else:
days = 31
return d <= days
# ---- tests ----
for d, m, y in [(29, 2, 2000), (29, 2, 1900), (29, 2, 2024), (31, 4, 2026), (31, 12, 2026), (0, 1, 2026), (15, 13, 2026)]:
print(f"{d}/{m}/{y}: {is_valid_date(d, m, y)}")
Learning objectives
By the end of this page you should be able to:
- Construct if, if-else and if-elif-else structures in Python, and if, else if and else in Java, to run different blocks of code.
- Use the relational operators <, <=, >, >=, == and != correctly, especially at boundary values.
- Combine conditions with the Boolean operators AND, OR and NOT, and evaluate them with truth tables.
- Explain why the order of elif conditions matters, and when nested selection is appropriate.
- Trace selection structures and choose test data (normal, boundary, abnormal) that exercises every branch.
Selection
Selection lets a program choose between paths. A condition (a Boolean expression) is evaluated; its result, True or False, decides which block runs.
if days_late <= 0: # tested first
status = "On time"
elif days_late <= 7: # tested only if the first was False
status = "Late: 0.5 per day"
elif days_late <= 30:
status = "Overdue: letter sent"
else: # runs if every condition was False
status = "Lost: replacement charge"
- if alone: run a block or skip it. if / else: exactly one of two blocks. if / elif / else: exactly one of many: the first condition that is True wins, and the rest are not even tested.
- A series of separate
ifstatements is different: each is tested, so several blocks may run. - Python marks blocks with a colon and indentation; Java uses parentheses around the condition and braces:
if (daysLate <= 0) { ... } else if (daysLate <= 7) { ... } else { ... } - Nested selection: an if inside another if, for decisions that only make sense after an earlier one (for example, check the member type only after confirming membership).
Relational operators
| Operator | Meaning | Example (days = 7) |
|---|---|---|
< | less than | days < 7 → False |
<= | less than or equal to | days <= 7 → True |
> | greater than | days > 7 → False |
>= | greater than or equal to | days >= 7 → True |
== | equal to (comparison) | days == 7 → True |
!= | not equal to | days != 7 → False |
Do not confuse = (assignment) with == (comparison): if days = 7: is a SyntaxError in Python. String comparison is case-sensitive: "Dune" == "dune" is False. In Java, compare Strings with .equals(), not ==.
Boolean operators
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
- Precedence: comparisons first, then
not, thenand, thenor. Use brackets to make your meaning clear:not has_fine and (age >= 16 or with_teacher). - Java writes them as
&&,||and!. - De Morgan's laws:
not (a and b)equalsnot a or not b;not (a or b)equalsnot a and not b.
Testing selection
Test every branch, with normal data (5 days late), boundary data on both sides of each limit (0, 1, 7, 8, 30, 31) and abnormal data (-3, "abc"). Most selection bugs live at the boundaries: < instead of <=.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. State the output when copies is (a) 0, (b) 2, (c) 5. [3]
if copies == 0:
print("Reserve")
elif copies < 3:
print("Few left")
else:
print("Available")
Reserve [1]; (b) Few left [1]; (c) Available [1].2. Outline the difference between three separate if statements and one if / elif / elif structure. [2]
3. Given a = 4, b = 9, member = False, evaluate: (a) a < 5 and b < 5, (b) a > 5 or not member, (c) not (a == 4 or b == 4). [3]
4. Construct a Python function loan_days(member_type) that returns 14 for "student", 28 for "teacher", 7 for "visitor" and 0 for anything else. [4]
if member_type == "student": return 14 [1]; elif member_type == "teacher": return 28 [1]; elif member_type == "visitor": return 7 [1]; else: return 0 [1]. Award marks for equivalent Java with else if and .equals().5. The study room may be used by a student who has no unpaid fine and who is either at least 16 or accompanied by a teacher. Construct the condition using has_fine, age and with_teacher. [3]
not has_fine [1] and (age >= 16 or with_teacher) [1]; brackets so that the OR is evaluated before the AND [1].6. Identify suitable boundary test data for the condition if days_late <= 7: and justify your choice. [3]