Proof Academy · Python · Journey 03

Selection and validation

Make a program choose what to do, then decide which inputs it can accept. Trace a decision, repair a bug and build a validator from scratch.

Two study sessions · Requires input and types

01 · Understand and predict

One input, one path

An if statement tests a condition. A condition is an expression that evaluates to True or False. In an if / elif / else chain, Python checks conditions from top to bottom and runs the first matching block. If no condition matches, it runs else. The indentation shows which lines belong to each block.

score = int(input())
if score < 0 or score > 10:
    print("Invalid score")
elif score >= 8:
    print("Gold badge")
else:
    print("Silver badge")

Worked trace · score is 11

  1. 11 < 0 is false. 11 > 10 is true.
  2. or needs at least one true condition, so Python prints Invalid score.
  3. Python skips elif and else. Putting the gold test first would incorrectly give 11 a gold badge.
Predict what the badge program prints when score is 8.
From code to machine. The Python runtime evaluates the comparison and follows the selected block. The underlying hardware executes machine instructions through fetch, decode and execute. This trace follows Python values and decisions. A source line can involve many machine instructions.

This badge example assumes the input can be converted to an integer. In the build task you’ll check the text before converting it.

Guided study

Read it, trace it, test it

Turn words into conditions

A comparison answers a yes-or-no question. Write age == 12 to test equality and age = 12 to assign a value. The two uses of the equals sign look similar, so read the whole line out loud. Other comparisons include != for “is different from”, < for “is below” and <= for “is at or below”. Phrases like “from 12 to 16 inclusive” mean both ends are accepted. Write age >= 12 and age <= 16 or the equivalent chained comparison 12 <= age <= 16.

Use and for requirements that must both hold. Use or where either condition is enough. To reject values outside 12 to 16, use age < 12 or age > 16. Check a number from the middle as well as each boundary. If you accidentally write age >= 12 or age <= 16, every integer satisfies at least one half. The code runs, but the decision rule is wrong.

Ageage >= 12age <= 16Both true?
11FalseTrueFalse
12TrueTrueTrue
15TrueTrueTrue
16TrueTrueTrue
17TrueFalseFalse

Order your checks

Read the input as text first. Check presence and format before using int(). Compare the numeric value with the allowed range only after conversion succeeds. For the locker task, .isdecimal() is a format check. It returns false for the empty string, a minus sign or a decimal point. It allows leading zeros, which the brief permits. A range check is a different decision. "31" can be converted successfully even when it is outside the allowed range.

entry = input()
if not entry.isdecimal():
    print("Check the format")
elif int(entry) <= 20:
    print("In range")
else:
    print("Too large")

Trace " 12", "020" and "21". The first starts with a space, so the format branch prints Check the format and Python skips the conversion. "020" passes the format check and converts to 20, which meets the inclusive limit. "21" passes format but exceeds the limit, so the final branch runs. The code allows 0 because the brief for this example supplies only an upper limit and the accepted format has no minus sign.

Keep separate decisions separate

An if / elif chain selects at most one branch. Two separate if statements can both run. Suppose a club offers a free badge for members and a free poster to anyone aged under 16. The same person might get both, so separate if statements can be appropriate. For a single ticket category, use one chain. Work out whether the brief requires one output or several before choosing the structure.

Practise a Paper 2 habit

A starter program should display Junior for ages under 12, Youth for 12 to 16, and Adult for 17 and above. Its first condition is age <= 16, followed by elif age < 12. Explain why a ten-year-old never gets Junior. Rewrite the conditions in the correct order. Choose three boundary inputs and predict their outputs. Then test one more age well away from a boundary to check the general case.

Validate while keeping the original evidence

Suppose a booking code must begin with B and have exactly four characters. Check len(code) == 4 first. A blank input cannot be indexed at position 0, but a false length condition short-circuits an and chain. Only after length passes do you inspect code[0] and the remaining characters. A format check answers whether the entry follows the rules, while a lookup answers whether it exists in a known list. A code can pass the format check and still be absent. Keep this distinction when interpreting messages such as Invalid format and Unknown code. To test the two paths separately, try one malformed code and one correctly formed code that you know is absent.

Check your guided practice

The first condition is true for 10, so Python runs that block and skips the later one. Use if age < 12 for Junior, then elif age <= 16 for Youth, followed by else for Adult. Useful cases are 11, 12, 16 and 17, with expected results Junior, Youth, Youth and Adult. You can then try 30 to confirm that the default branch works for values beyond the immediate boundary. This exercise assumes the age has already been validated as a non-negative integer.

02 · Run and repair

Find the bug at the boundary

A race accepts ages 12 to 16 inclusive. The starter expects a whole-number age. Run it with 17 and explain why it prints Enter. Change the condition so both limits have to be met, then check values at and just outside the boundaries. Keep the output messages unchanged.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Write the two limits separately. An age has to meet both limits. Try tracing 17 through each comparison.

03 · Build independently

Validate a locker number

Write a program that reads one line of text and prints exactly one message. The system accepts locker numbers 1 to 30 inclusive. A number may have leading zeros. For this exercise, a valid entry uses decimal digits only, without spaces or a sign.

  • Print Whole number needed if the entry is blank or includes anything other than decimal digits.
  • Print Outside range if it is a whole number outside 1 to 30.
  • Print Accepted if it is within range.

Plan the checks in order. entry.isdecimal() checks that the string contains one or more decimal digits. Use int(entry) only after that check passes. Use plain input() so the displayed output is just your result.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Read the input into a variable. Check it with .isdecimal() before using int(). Then check the converted number against the two limits.

04 · Explain and transfer

Show why your tests matter

Explain why both 30 and 31 belong in your test plan, and why running only those tests would miss the error caused by a blank entry.

Compare your explanation

30 checks that the last legal number is accepted. 31 checks that the next number is rejected. Both convert successfully, so neither checks that blank text is rejected before conversion.

Independent follow-up. Adapt your validator for museum group bookings of 2 to 24 people. Before you run it, write down two accepted inputs, two values immediately outside the range and one input that should be rejected before conversion.

These are original GCSE practice tasks. The workspace runs Python in your browser and keeps drafts in this view. Download your .py file before leaving.

Next: loops and running totals →