Writing and Refining Algorithms
A flag variable is a variable that records whether something has happened. It usually holds True or False. You set it before a loop, change it inside the loop when the event happens, and check it in the loop's condition or afterwards to decide what happens next.
A while loop checks its condition before the first pass, so it might not run at all. If a loop must run at least once, you can use a flag that starts as True. The condition is true the first time, so the loop always runs. Inside the loop, when the job is finished, set the flag to False. The condition then becomes false and the loop stops.
The flag must be changed inside the loop. If it stays True, the condition never becomes false and the loop never ends.
playing = True
while playing:
guess = int(input("Guess a number from 1 to 10: "))
if guess == 7:
playing = False
print("You found the lucky number!")Output when the user types 3, 7:
Guess a number from 1 to 10: 3
Guess a number from 1 to 10: 7
You found the lucky number!
In this example, playing is the flag. It starts as True, so the loop asks for a guess at least once. When 7 is guessed, playing is set to False inside the loop, which ends it.
OCR GCSE Computer Science · Writing and Refining Algorithms
OCR GCSE Computer Science · Condition-Controlled Iteration
OCR GCSE Computer Science · Defensive Design