Lesson 6 of 10
Programming: Lesson 6

Condition-Controlled Iteration: WHILE Loops

Repeating until a condition becomes False. This lesson covers WHILE loop syntax, validation loops, sentinel values and when to choose WHILE over FOR - the decision that GCSE mark schemes test every year.

50 minutes Python + C# toggle
Language: Saved automatically

A login screen does not ask for your password exactly three times. It asks until you get it right - or until you have failed too many times. You cannot use a FOR loop for this because you have no idea how many attempts the user will need. A WHILE loop keeps asking until a condition changes. Every input validation routine in every real program uses this pattern: keep asking until the answer is valid. Without WHILE loops, programs cannot handle the unpredictability of real users.

Think about it: A program asks the user to enter a number between 1 and 10. The user might enter 0, or -5, or "hello". How many times do you need to ask? You cannot know in advance. Write down in English what the loop should do each time around - then look for that pattern in the code.
Terms you need to know
Condition-controlled loop
A loop that repeats until a condition becomes False. The number of iterations is not known in advance.
WHILE loop
Checks the condition BEFORE each iteration. If the condition is False from the start, the body never executes.
Infinite loop
A loop whose condition never becomes False. The program runs forever (or crashes). Usually a bug.
Validation loop
A WHILE loop that keeps asking for input until the user provides a valid response.
Sentinel value
A special value that signals "stop". E.g. entering -1 or "quit" to end a loop that collects numbers.
Loop invariant
A condition that is True before the loop, true after each iteration, and true when the loop exits - useful for reasoning about loop correctness.
Condition-controlled repetition

A WHILE loop checks the condition before each iteration. If the condition is False when first reached, the body never runs. If the condition never becomes False, the loop runs forever.

# Basic WHILE: count up to 5
count = 1
while count <= 5:
    print(count)
    count += 1    # CRITICAL: update the variable that controls the condition
print("Done")

# Validation loop: keep asking until valid input
age = int(input("Enter age (1-120): "))
while age < 1 or age > 120:
    print("Invalid! Must be between 1 and 120.")
    age = int(input("Enter age (1-120): "))
// C# while loop: count up to 5
int count = 1;
while (count <= 5)
{
    Console.WriteLine(count);
    count++;    // CRITICAL: update the variable
}

// Validation loop
Console.Write("Enter age (1-120): ");
int age = int.Parse(Console.ReadLine());
while (age < 1 || age > 120)
{
    Console.WriteLine("Invalid! Must be between 1 and 120.");
    Console.Write("Enter age (1-120): ");
    age = int.Parse(Console.ReadLine());
}
The infinite loop trap

The most common WHILE bug: forgetting to update the variable that controls the condition. If count never increases, while count <= 5 is always True, and the program runs forever. Every WHILE loop needs something inside it that can eventually make the condition False.

When to use each loop

A sentinel value is a special input that signals the end of the loop. It is used when the number of inputs is unknown - a user keeps entering values until they type -1 or "quit".

# Sentinel loop: collect scores until -1 is entered
total = 0
count = 0
score = int(input("Enter score (-1 to stop): "))
while score != -1:
    total += score
    count += 1
    score = int(input("Enter score (-1 to stop): "))
if count > 0:
    print("Average:", total / count)
// C# do-while: body runs at least once (good for menus)
string choice;
do
{
    Console.WriteLine("1. Play  2. Settings  3. Quit");
    choice = Console.ReadLine();
    // process choice...
} while (choice != "3");
FOR vs WHILE - the mark scheme question

Examiners often ask: "Why is a WHILE loop more appropriate than a FOR loop here?" The answer is always about predictability: use FOR when you know the exact number of repetitions before the loop starts (e.g. process 10 students, print the 12-times table). Use WHILE when you do not know in advance how many iterations are needed (e.g. validation, sentinel value, game loop, waiting for a condition).

Validation Loop Simulator
Input Validation Simulator
Set a valid range and enter values to see the WHILE loop accept or reject each one.
Min value
Max value
Your input
The WHILE loop is waiting for a valid value between 1 and 100...

Three Quick Challenges

Predict the output

How many times does the loop run and what is printed?

n = 1
while n < 32:
    n *= 2
print(n)
int n = 1;
while (n < 32) n *= 2;
Console.WriteLine(n);
Fill in the blank

Complete the validation loop - it should keep asking until the user types something other than "quit":

user_input = input("Command: ") while user_input "quit": user_input = input("Command: ")
while (userInput "quit") { userInput = Console.ReadLine(); }
Spot the bug

This loop never ends. What is wrong?

count = 0
while count < 5:
    print(count)
    count += 2

Test yourself

1. x = 10. WHILE x > 0: print(x). What is missing to prevent an infinite loop?

Without x -= 1, x stays at 10 forever, so x > 0 is always True. The loop runs infinitely. Adding x -= 1 inside the loop body decrements x each iteration until it reaches 0, at which point the condition becomes False and the loop exits.

2. A validation loop keeps asking for a password until it equals "CodeBash99". Which loop is correct?

The loop should continue while the password is WRONG (!=). Using == would loop while the password is correct - the opposite of what we want. A FOR loop is wrong because we do not know how many attempts are needed. IF is not a loop - it only checks once.

3. What is a sentinel value?

A sentinel value (like -1 or "quit") is a special input that the user enters to signal they are finished. It is not a real data value but a control signal. The loop keeps running while the input is NOT the sentinel value.

4. If a WHILE loop's condition is False before it starts, how many times does the body execute?

A WHILE loop checks the condition BEFORE each iteration. If it is False from the start, the body is skipped entirely (zero executions). This is different from a DO-WHILE loop in C#, which always executes the body at least once before checking the condition.

5. Why is a WHILE loop better than a FOR loop for a menu that keeps showing until the user chooses "Quit"?

A FOR loop requires knowing the number of iterations in advance. A menu continues as long as the user has not chosen to quit - that could be 1 time or 100 times. Since the count is unknown in advance, a condition-controlled WHILE loop is the correct choice.
Challenge question

A student writes a number guessing game using a WHILE loop. The secret number is 42. The program should give the user up to 5 guesses, stopping either when they guess correctly OR when they have used all 5 attempts. Write the complete program in pseudocode or Python. What combination of conditions controls the WHILE loop?

Python solution:
secret = 42
attempts = 0
guess = -1
while guess != secret and attempts < 5:
    guess = int(input("Guess: "))
    attempts += 1
    if guess < secret: print("Too low")
    elif guess > secret: print("Too high")
if guess == secret: print("Correct in", attempts, "attempts!")
else: print("Out of guesses. The number was", secret)

The compound condition: guess != secret AND attempts < 5 - continue while the guess is wrong AND there are attempts left. The loop exits when EITHER condition is False (correct guess OR out of attempts). This requires both an AND condition in the WHILE and an IF/ELSE after to distinguish the two exit reasons.
Printable Worksheets

Practice what you have learned

Three levelled worksheets. Download, print and complete offline.

Recall
WHILE Loop Structures
Trace WHILE loops, identify missing update statements and complete loop condition tables.
Download
Apply
Validation and Sentinel Loops
Write validation routines, sentinel-controlled collection programs and number guessing games.
Download
Exam Style
Exam-Style Questions
Trace WHILE loops, correct infinite loop bugs, justify loop type choice and write loop conditions for described scenarios.
Download
Lesson 6 - Programming
WHILE Loops
Starter activity
Ask: "I want to ask a user for a number between 1 and 10, and keep asking until they give a valid answer. Should I use a FOR or WHILE loop? Why?" Take responses, then reveal: FOR requires knowing the count in advance - you do not. WHILE is the right choice. This establishes the core FOR vs WHILE decision before any syntax is shown.
Lesson objectives
1
Write WHILE loops with correct condition syntax in Python and C#.
2
Identify and fix infinite loop bugs (missing variable update).
3
Write validation loops that reject invalid input.
4
Use sentinel values to control input-collection loops.
5
Justify when a WHILE loop is more appropriate than a FOR loop.
Key vocabulary
Condition-controlled loop
Repeats while a condition is True. Number of iterations not known before starting.
Sentinel value
Special input (e.g. -1, "quit") that signals the loop to end. Not a data value - a control signal.
Discussion questions
What is the single most important rule for writing a while loop that never causes an infinite loop?
Why is a sentinel value a clean way to end a loop compared to asking the user "do you want to continue?"
When would a do-while style loop be more natural than a standard while loop? How do you simulate it in Python?
Exit tickets
Write a WHILE loop that counts from 1 to 10 printing only odd numbers. [3 marks]
A student writes: while x != 0: print(x). The loop runs forever with x = 5. What is the bug and the fix? [2 marks]
Explain why WHILE is better than FOR for collecting exam scores until the teacher enters -1. [2 marks]
Homework suggestion
Write a number guessing game: the program picks a random number between 1 and 100, and the user guesses. After each guess, output "Too high", "Too low" or "Correct!" Keep going until correct, counting guesses. At the end, tell the user how many guesses it took. Optionally: limit to 10 guesses.