While loops
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
Common mistakes
- Change something inside the loop so the condition can become false, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
Now you try
- Make sure your condition will eventually become false.
- Stuck on the loop? Do the short drill Finish the countdown first. It is one missing line.
- Press Check answer to test your code.
A while loop builds up a value
A while loop repeats until its condition is false.
Use a while loop to count down. Each turn, print the value of count, then make count one smaller. Stop when it reaches 0, so the output is 5, 4, 3, 2, 1 — one per 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. · 実行ボタンをクリックして出力を確認してください。
Start n at 1 and add 1 each pass. The loop stops too soon: it ends while n is still 1. Change the condition so it keeps going while n * n is at most 50. When it stops, n is the first whole number whose square is over 50.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Same answer, with break. n starts at 1 inside while True:. The if is already inside the loop and n grows after it. Change the condition so you break when n * n is greater than 50. Leave the answer in n (it is 8). Do not add 1 before the test — that makes the answer 9.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Start with n = 1 and steps = 0. While n is smaller than 1000, double n and add 1 to steps. When the loop ends, n is 1024. How many doublings did it take? Leave the answer in steps.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。