While loops
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Loop while a condition is true
- A
whileloop repeats as long as its condition is true. - It checks the condition before each pass.
- Use it when you do not know the number of repeats in advance.
Always change the condition
- Something inside the loop must move toward making the condition false.
- If it never becomes false, the loop runs forever (an infinite loop).
- Press Stop if a loop ever gets stuck.
count = 3
while count > 0:
print(count)
count = count - 1
break and continue
breakstops the loop right away.continueskips the rest of this pass and goes to the next one.while True:loops forever until abreakends it.
n = 0
while True:
n = n + 1
if n == 4:
break
print(n)
Checking before or after
- A
whileloop checks first, so it may run zero times. - A "repeat until" loop checks after, so it always runs at least once.
- Python has no
repeat; usewhile True:with abreakat the end.
In Cambridge pseudocode
whileis the pre-condition loop;REPEAT … UNTILis the post-condition loop.
count ← 3
WHILE count > 0
OUTPUT count
count ← count - 1
ENDWHILE
REPEAT
OUTPUT count
count ← count + 1
UNTIL count = 3
Now you try
- Make sure your condition will eventually become false.
- Press Check answer to test your code.
Use a while loop to print a countdown from 5 down to 1, each number on its own line.
Click Run to see the output here.
Use a while loop to add up the numbers 1 to 10. Store the total in total (the answer is 55).
Click Run to see the output here.
Use while True: with a break to find the smallest whole number n (starting at 1) whose square n * n is greater than 50. Leave the answer in n (it is 8).
Click Run to see the output here.