Lessons · Python · while loops
Repeat until something changes
while condition: repeats as long as the condition is true. Use it when you do not know in advance how many times.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Reading until end of file, retrying until success, a game loop, walking a linked structure: all 'until', not 'this many times'.
How to think about it
When should this stop, and what moves it there? Write the stopping condition first, in English. Then make sure something inside the loop moves toward it every time, or you have written forever.
Worked example
n = 27; steps = 0The Collatz walk: until n reaches 1.
while n != 1:Stop condition.
n = n // 2 if n % 2 == 0 else 3 * n + 1Something changes each turn.
steps += 1Count.
print(steps)111.
Your turn
Keep halving until below 1.
while x 1:
x = x / 2Solve one with the tests running
The trap
Forgetting to change the variable in the condition. The loop never ends; on a phone the tab hangs.
Practise while loops on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.