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.
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.
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 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.
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");
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).
Three Quick Challenges
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);
Complete the validation loop - it should keep asking until the user types something other than "quit":
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?
2. A validation loop keeps asking for a password until it equals "CodeBash99". Which loop is correct?
3. What is a sentinel value?
4. If a WHILE loop's condition is False before it starts, how many times does the body execute?
5. Why is a WHILE loop better than a FOR loop for a menu that keeps showing until the user chooses "Quit"?
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?
secret = 42attempts = 0guess = -1while 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.Practice what you have learned
Three levelled worksheets. Download, print and complete offline.