SDD  ·  Software Design & Development

Conditional Loops

Lesson 10 of 19 Approx 60 min Requires: SDD7 Selection, SDD8 Complex Conditions, SDD9 Fixed Loops 🚀 Extension Studio
Learning intentions
  • Understand what a conditional loop is and when it is the appropriate loop to use
  • Write conditional loops in Python and read WHILE and REPEAT…UNTIL in SQA reference language
  • Apply conditional loops to solve input validation problems
Success criteria
  • I can explain the difference between a fixed loop and a conditional loop, and choose the correct one for a given problem
  • I can write a Python while loop and trace a WHILE loop in SQA reference language
  • I can read a REPEAT…UNTIL loop in SQA reference language and write its Python equivalent
  • I can write an input validation routine using a conditional loop
  • I can trace a conditional loop step by step and state the final output
Warm up — what do you already know?

Answer before the lesson begins. These check prior knowledge from earlier lessons — it's fine if you're unsure.

1. A program needs to add up numbers entered by the user. It will stop when the user types −1. Before writing the code, can you work out how many times the loop will run?

2. Which Python operator checks whether two values are not equal?

3. What is a boolean expression?

Key vocabulary

conditional loop
A loop that repeats while a condition is true (or until a condition becomes true). The number of iterations is not known in advance.
WHILE loop
A conditional loop that checks its condition before each iteration. If the condition is false at the start, the loop body never runs.
REPEAT…UNTIL
A conditional loop that checks its condition after each iteration. The loop body always runs at least once.
loop condition
The boolean expression that controls whether a conditional loop continues. Evaluated before each iteration (WHILE) or after (REPEAT…UNTIL).
input validation
Checking that user input is within acceptable bounds and re-requesting it if not. Conditional loops are the standard tool for this.
sentinel value
A special value that signals the end of input, such as −1 or "quit". The loop continues until the sentinel is entered.
infinite loop
A loop whose condition never becomes false (or true for UNTIL), so it runs forever. It can be caused by forgetting to update the variable the condition depends on.

Conditional Loops

SQA uses reference language in question papers. You need to be able to read it. You will never be asked to write it. Write Python for implementation questions; design questions use structured-English pseudocode.

What is a conditional loop?

A conditional loop (also called a condition-controlled loop) repeats a block of code while a condition is true — or until a condition becomes true. The defining feature is that you do not know in advance how many times the loop will run. The number of iterations is determined by what happens during the program's execution, not by a fixed number set before the loop starts.

Conditional loops are the right choice when:

  • You want to keep asking the user for input until they enter a valid value (input validation)
  • You want to keep processing data until a special "stop" value (sentinel) is entered
  • You want to repeat an action until some condition is met

If you already know exactly how many times the loop should run — for example, always 5 scores or always 10 table entries — a fixed loop (SDD9) is the correct choice instead.

The WHILE loop

The WHILE loop checks its condition before each iteration. If the condition is false the very first time it is checked, the loop body never runs at all.

SQA reference language (read only)

Read this syntax pattern; it is not a writing template.

WHILE condition DO
    <loop body>
END WHILE

Python syntax:

while condition:
    pass  # replace with the indented loop body

The condition is a boolean expression. The loop continues repeating as long as the condition evaluates to True. As soon as it evaluates to False, the loop ends and execution continues with the first line after END WHILE (or after the Python loop's indented block).

Key point: the loop body must contain code that can eventually make the condition false. If not, the loop runs forever — this is called an infinite loop.

Where is the condition checked? WHILE check condition run loop body leave loop true false May run zero times if the condition is false at the start. REPEAT...UNTIL run loop body check condition leave loop true false Always runs at least once because the check comes after the body.

The REPEAT…UNTIL loop

The REPEAT…UNTIL loop checks its condition after each iteration. This means the loop body always runs at least once, regardless of the condition. The loop continues until the condition becomes true — it repeats while the condition is false.

SQA reference language (read only)

Read this syntax pattern; it is not a writing template.

REPEAT
    <loop body>
UNTIL condition

This is different from a WHILE loop in a subtle but important way: WHILE continues while the condition is true; REPEAT…UNTIL continues until the condition becomes true (i.e., while it is false).

Python equivalent: Python has no built-in REPEAT…UNTIL construct. The closest pattern uses while True with a break:

while True:
    # loop body (always runs at least once)
    if condition:
        break

Read REPEAT…UNTIL in question papers. In Python, either use a while loop that tests the input collected before it, or use while True with a break after the body. Choose a pattern whose logic matches the task.

Input validation — the most important pattern

Input validation is one use of conditional loops. Read this reference-language example: it asks again while the value is outside the acceptable range. Then compare the Python implementation below.

SQA reference language (read only)

RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 0 OR score > 100 DO
    SEND "Invalid — enter a value between 0 and 100" TO DISPLAY
    RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE

In Python:

score = int(input("Enter score (0–100): "))
while score < 0 or score > 100:
    print("Invalid — enter a value between 0 and 100.")
    score = int(input("Enter score (0–100): "))
print("Valid score:", score)

In this pattern, one input statement is before the loop and another is inside it. The inner statement runs whenever an invalid value is rejected. The condition needs an assigned value before its first check; a different valid pattern can initialise a variable before the loop or use while True with a break.

Input validation pattern: repeat while the value is invalid receive score score invalid? < 0 OR > 100 yes show error receive score again no accept score The WHILE condition describes the bad case. while score < 0 or score > 100:

Sentinel values

A sentinel value is a special value that signals the end of input — for example, entering −1 to stop adding numbers. The loop checks for the sentinel after each input and stops when it is detected:

total = 0
number = int(input("Enter a number (–1 to stop): "))
while number != -1:
    total = total + number
    number = int(input("Enter a number (–1 to stop): "))
print("Total:", total)

The sentinel value itself (−1) is never added to the total — the condition is checked before the addition.

Comparing fixed and conditional loops

FeatureFixed loopConditional loop
Number of iterationsKnown before the loop startsUnknown — depends on the condition
When to useRepeat an exact number of timesRepeat until something changes
SQA reference language (read only)FOR … TO … DOWHILE … DO or REPEAT … UNTIL
Python keywordforwhile
Condition checkedNot applicableBefore each iteration (WHILE) or after (REPEAT…UNTIL)
May never run?Reference-language FOR: runs if start ≤ end. Python range: can be empty because its end is excluded.WHILE: yes. REPEAT…UNTIL: no

Worked examples

Example 1 — Simple WHILE loop: count up to a user's number

Write Python code that asks the user to enter a positive whole number, then counts from 1 up to it. Read the supplied SQA reference language to compare the same logic; do not write reference language.

1
SQA reference language (read only):
RECEIVE limit FROM (INTEGER) KEYBOARD
SET count TO 1
WHILE count <= limit DO
    SEND count TO DISPLAY
    SET count TO count + 1
END WHILE
2
Python:
limit = int(input("Enter a number: "))
count = 1
while count <= limit:
    print(count)
    count = count + 1
3
If the user enters 4, the output is: 1 2 3 4 (each on its own line). The loop ends when count becomes 5, because 5 <= 4 is false. If the user entered 0, the loop body would never run because 1 <= 0 is immediately false.
Example 2 — Input validation: score between 0 and 100

Read the supplied SQA reference language and compare its Python implementation. A program collects an exam score from the user. The score must be between 0 and 100 inclusive. If the user enters an invalid value, the program should display an error message and ask again.

1
SQA reference language (read only):
RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 0 OR score > 100 DO
    SEND "Invalid — enter a value between 0 and 100" TO DISPLAY
    RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE
SEND "Score accepted: " & score TO DISPLAY
2
Python:
score = int(input("Enter score (0–100): "))
while score < 0 or score > 100:
    print("Invalid — enter a value between 0 and 100.")
    score = int(input("Enter score (0–100): "))
print("Score accepted:", score)
3
If the user enters −5, then 110, then 75: the loop runs twice (rejecting −5 and 110), then stops when 75 is entered because 75 < 0 OR 75 > 100 is False OR False = False. The program prints Score accepted: 75.
Example 3 — REPEAT…UNTIL: guess the number

Read the SQA reference language below, then compare its Python equivalent. Both ask the user to guess 42 and keep asking until the guess is correct. Trace inputs 20, 60, 42: which messages appear?

1
SQA reference language (read only):
REPEAT
    RECEIVE guess FROM (INTEGER) KEYBOARD
    IF guess < 42 THEN
        SEND "Too low — try again" TO DISPLAY
    ELSE IF guess > 42 THEN
        SEND "Too high — try again" TO DISPLAY
    END IF
UNTIL guess = 42
SEND "Correct!" TO DISPLAY
2
Python equivalent (using while True + break):
while True:
    guess = int(input("Guess the number: "))
    if guess < 42:
        print("Too low — try again.")
    elif guess > 42:
        print("Too high — try again.")
    else:
        break
print("Correct!")
3
The loop always runs at least once — the user must guess at least once before the condition can be checked. For inputs 20, 60, 42, the messages are Too low — try again, Too high — try again, then Correct! (the Python messages include full stops after the first two). When guess == 42, the break exits the loop and print("Correct!") runs. Note: in SQA reference language, UNTIL guess = 42 means "stop when the guess equals 42" — opposite in phrasing from a WHILE condition.
Example 4 — Sentinel value: sum numbers until −1 is entered

Read the supplied SQA reference language and compare its Python implementation. A program asks the user to enter positive numbers one at a time. When the user enters −1, the program stops and displays the total of all numbers entered.

1
SQA reference language (read only):
SET total TO 0
RECEIVE number FROM (INTEGER) KEYBOARD
WHILE number <> -1 DO
    SET total TO total + number
    RECEIVE number FROM (INTEGER) KEYBOARD
END WHILE
SEND "Total: " & total TO DISPLAY
2
Python:
total = 0
number = int(input("Enter a number (–1 to stop): "))
while number != -1:
    total = total + number
    number = int(input("Enter a number (–1 to stop): "))
print("Total:", total)
3
If the user enters 10, 20, 5, −1: the loop runs 3 times. After iteration 1: total = 10. After iteration 2: total = 30. After iteration 3: total = 35. When −1 is entered, the condition −1 != −1 is false, so the loop ends. Output: Total: 35. The −1 is never added because the condition is checked before the addition.
Now you try

A bank ATM asks the user to enter their PIN. The PIN must be a 4-digit number — that is, a whole number between 1000 and 9999 inclusive. If the user enters a number outside this range, the ATM should display an error message and ask again. Once a valid PIN is entered, the ATM should display "PIN accepted".

Answer the following:

  1. Why is a conditional loop more appropriate than a fixed loop here?
  2. Write Python code that rejects invalid values and asks again.
  3. Trace your code with inputs 999, 10000, then 1234. What is displayed?
  1. A conditional loop is needed because you do not know in advance how many times the user will enter an invalid PIN. The loop must repeat until the user provides a valid value — the number of iterations depends entirely on the user's input.
  2. pin = int(input("Enter your PIN: "))
    while pin < 1000 or pin > 9999:
        print("Invalid PIN — must be a 4-digit number.")
        pin = int(input("Enter your PIN: "))
    print("PIN accepted.")
  3. 999 and 10000 are outside 1000–9999, so each produces Invalid PIN — must be a 4-digit number. The next input, 1234, is valid: the loop ends and displays PIN accepted. Equivalent Python solutions with this behaviour are valid.
Common mistakes
✕
Only collecting input inside the loop (not before it). With a WHILE loop, the condition is checked before the first iteration. If the variable used in the condition has never been assigned a value, Python will throw a NameError. For the read-before-loop pattern, collect input before the loop and again inside it. Initialising the variable before the loop or using while True with a break can also work; the variable must be assigned before a condition reads it.
✕
Forgetting to update the loop variable inside the loop body. If the variable that the condition depends on never changes, the condition stays true forever — creating an infinite loop. For input validation, re-reading the input inside the loop is what allows the condition to eventually become false.
✕
Confusing WHILE and UNTIL conditions. A WHILE loop continues while the condition is true — so for validation, the condition should describe the invalid state (score < 0 OR score > 100). A REPEAT…UNTIL loop continues until the condition becomes true — so the condition describes the valid state (score >= 0 AND score <= 100). These are the logical opposites of each other.
✕
Using a fixed loop when the number of repetitions is unknown. A fixed loop requires knowing how many iterations to run before the loop starts. If the number depends on user behaviour (e.g. how many invalid entries they make), a fixed loop cannot handle this correctly. Always identify whether the repetition count is known in advance — if not, use a conditional loop.
Exam tip

For input validation, choose a conditional loop whose logic keeps asking until the value is valid. Read-before-loop and post-conditional patterns can both work. Write Python when asked for code; use structured-English pseudocode for a design task, accepting any clear equivalent design. Read and trace formal SQA reference language when it is supplied in a question.

When writing WHILE loop conditions for validation, remember the condition describes the invalid case. For example, if a valid age is 0–120, the loop condition is age < 0 OR age > 120. A common error is writing the valid condition instead (age >= 0 AND age <= 120), which repeats for a valid value and exits for an invalid value — the opposite of the required behaviour.

For trace questions involving WHILE loops, draw a table with a row for each iteration and note the values after each pass. State clearly when the condition becomes false and the loop terminates. Remember — the loop body does not run on the final check, when the condition fails.

Task Set

Questions 1–5 are auto-checked. Questions 6–8 are self-marked — write your answer, then reveal the model answer to check your work. Questions 9–10 are practical PyCharm implementation tasks.

1. A program uses a WHILE loop. When does the condition get checked? TYPE 1

2. What is the key difference between a WHILE loop and a REPEAT…UNTIL loop? TYPE 1

3. What does the following code print if the user enters 3, then 7, then 5? TYPE 1

number = int(input("Enter number: "))
while number != 5:
    print(number)
    number = int(input("Enter number: "))
print("Done")

4. A program uses a WHILE loop for input validation. The valid range for a temperature is −20 to 40. Which condition should the WHILE loop use? TYPE 1

5. A program uses the read-before-loop Python while pattern to collect numbers until 0 (the sentinel). Where are its input statements placed? TYPE 1

6. Explain what would happen if a programmer wrote a WHILE loop for input validation but forgot to include a second input statement inside the loop body. TYPE 2

If the input is not collected again inside the loop body, the variable never changes. The first input stays the same on every check. If the initial value is invalid (causing the condition to be true), the condition will remain true on every subsequent check, because the value never updates. This creates an infinite loop — the program appears to freeze and never progresses to the code after the loop. The programmer must re-read the input inside the loop so that the user has the chance to enter a valid value, allowing the condition to eventually become false.

7. Write Python code for a program that asks the user to enter their age. The age must be between 0 and 120 inclusive. The program should keep asking until a valid age is entered, then display a confirmation message. TYPE 2

age = int(input("Enter age (0–120): "))
while age < 0 or age > 120:
    print("Invalid age — enter a value between 0 and 120.")
    age = int(input("Enter age (0–120): "))
print("Age accepted:", age)

Key points: input is collected before the loop (so the condition has a value to check); the WHILE condition describes the invalid state; input is collected again inside the loop body to allow a new value each iteration; the confirmation message is after the loop. Any equivalent Python solution that rejects invalid ages, asks again, and confirms a valid age is acceptable.

8. SQA reference language (read only) — Read and trace the following supplied code. Assume the user enters: 150, −5, 72. Show the values of score at each point and state what is finally displayed. TYPE 2

RECEIVE score FROM (INTEGER) KEYBOARD
WHILE score < 0 OR score > 100 DO
    SEND "Invalid." TO DISPLAY
    RECEIVE score FROM (INTEGER) KEYBOARD
END WHILE
SEND "Accepted: " & score TO DISPLAY
StepscoreNext condition check (score < 0 OR score > 100)Output
Initial input150True (150 > 100)—
Iteration 1150 → −5True (−5 < 0)Invalid.
Iteration 2−5 → 72False (72 is valid)Invalid.
Loop ends72—Accepted: 72

The loop runs twice (rejecting 150 and −5). When 72 is entered, the condition 72 < 0 OR 72 > 100 is False OR False = False, so the loop ends. Final output: Accepted: 72

9. Practical: In PyCharm, create a new Python file called sdd10_while.py and write a program that collects test scores from the user one at a time. The user signals they are finished by entering −1. The program should then display the total number of scores entered and the average. If no scores are entered (the user immediately types −1), display a suitable message instead. Test with 70, 85, 60, then −1; also test −1 immediately. Record the output from both tests below. TYPE 3

total = 0
count = 0
score = float(input("Enter score (–1 to finish): "))
while score != -1:
    total = total + score
    count = count + 1
    score = float(input("Enter score (–1 to finish): "))
if count > 0:
    average = total / count
    print("Scores entered:", count)
    print("Average:", average)
else:
    print("No scores were entered.")

Expected outputs: for 70, 85, 60, −1, display Scores entered: 3 then Average: 71.66666666666667. For −1 immediately, display No scores were entered.

The sentinel −1 is never added to total because the condition is checked before adding. The if count > 0 guard prevents a division-by-zero error if the user enters −1 immediately. float() is used so decimal scores are accepted.

10. Practical: In sdd10_while.py, type the buggy code below and run it to observe the problem. Then explain why the loop is skipped and why its condition is wrong, fix the code, and run again to confirm the corrected behaviour. Use corrected-code tests −2, 0, 5 and 3 immediately. Record the buggy output and both corrected outputs below. TYPE 3

number = 0
while number > 0:
    number = int(input("Enter a positive number: "))
print("You entered:", number)

Why the loop is skipped: number is initialised to 0. The WHILE condition is number > 0, which is 0 > 0 = False. With the supplied condition, the loop body never runs, so the user is never asked for input and the program immediately prints You entered: 0.

Wrong condition: The loop should repeat while the number is invalid (i.e. 0 or below). The correct condition is number <= 0, not number > 0. With the current condition, a positive number would cause another iteration and a non-positive number would end the loop. The initial zero masks that reversed behaviour. Zero itself can be a valid initial value if the condition is corrected to number <= 0; that is an alternative solution with input collected inside the loop.

Corrected code:

number = int(input("Enter a positive number: "))
while number <= 0:
    print("Invalid — must be greater than 0.")
    number = int(input("Enter a positive number: "))
print("You entered:", number)

The corrected read-before-loop pattern asks for input before checking it. With −2, 0, 5, display Invalid — must be greater than 0. twice, then You entered: 5. With 3 immediately, display only You entered: 3. The original buggy code displays You entered: 0 without asking for input.

Teacher notes — Shift+T to hide

Suggested timing: 60 minutes. Warm up 10 min; notes + comparison table 15 min; worked examples 15 min; now you try 5 min; task set 15 min.

Key misconception to address: The WHILE condition for input validation should describe the invalid case, not the valid case. Pupils frequently write while score >= 0 and score <= 100: and then find it repeats for valid scores and accepts invalid ones. A useful framing: "the WHILE condition is a bouncer — it lets people in (continues) when the situation is bad, and stops (exits) when it is good."

Live demo suggestion: Demonstrate an infinite loop live in Python — write a WHILE loop where the input line inside the body is missing. Show the terminal hanging. Then add the missing line and re-run. The contrast makes the "must update inside the loop" rule memorable. Run in a terminal or REPL.it so pupils can see the program freeze.

Extension question: Ask pupils to combine a conditional loop with a running total: write a program that keeps collecting scores (validating each one to 0–100) until the user enters −1, then outputs the average of all valid scores entered. This chains the sentinel pattern with the validation pattern.

REPEAT…UNTIL note: Python has no native REPEAT…UNTIL construct. Pupils read and trace REPEAT…UNTIL in SQA reference language; they never write it. For implementation, teach the Python equivalent (while True: ... if condition: break) alongside the read-before-loop pattern. Design answers use structured English.

SQA command words covered: "write" (Python), "trace" (Q8), "identify" (Q10 bug-finding), "explain" (Q6, Q10).