Repeating with while¶
~15 min ยท prerequisite: if, elif, and else
What you will be able to do¶
- Write a
whileloop that repeats its block as long as a condition staysTrue. - Update a counter inside the loop so the condition eventually becomes
False. - Recognize an infinite loop and stop it by changing the code that controls the condition.
The idea¶
A while loop starts with the word while, a condition, and a colon. Its block is indented, as in an if statement. Python checks the condition before each round. If the condition is True, Python runs the block once and then checks the condition again. When the condition is False, the loop ends, and Python continues with the first line after the block.
If the condition is False from the start, the block never runs. This is different from an if statement only in that the block can run many times.
The block must change something that the condition depends on. A variable that counts rounds is called a counter. A counter often starts at a value, goes up or down by one each round, and the loop stops when it reaches a limit.
Python has a short form for updating a variable. The augmented assignment count += 1 means the same as count = count + 1. The forms -=, *=, and //= work the same way, using subtraction, multiplication, and floor division.
If nothing in the block changes the condition, the condition stays True forever. This is an infinite loop. A program in an infinite loop keeps running until you stop it. In a terminal, you can press Ctrl+C to stop it, and Python then prints a traceback that ends with KeyboardInterrupt.
Worked example¶
Line by line, this is what Python does:
count = 1stores 1 in the counter.while count <= 3:checks the condition. 1 is at most 3, so the block runs.print("Round", count)showsRound 1.count += 1changescountto 2. Then Python goes back to the condition.- The same steps repeat for
countequal to 2 and 3. Whencountbecomes 4, the condition isFalse, and the loop ends. print("Done")runs after the loop.
The output is:
Try it¶
Each block checks its result with assert.
The first block adds the numbers 1 to 5 by changing n each round. The second block never runs its body, because the condition is False at the start. The third block doubles value until it reaches 100 or more, and counts the doublings.
Common mistakes¶
-
Forgetting to update the counter. The following loop never ends:
istays 0, soi < 3is alwaysTrue. The output is an endless stream of0. Press Ctrl+C to stop it. The loop never ends, so do not run this block in the browser runner. -
Stopping one round too early. The following check fails:
The loop runs for
countequal to 1 and 2, soroundsis 2. Usecount <= 3if you want three rounds. -
Writing
=+instead of+=. The linecount =+ 1does not add 1. It meanscount = +1, which stores 1. The following check fails:Write
count += 1to add 1 to the value. -
Expecting the loop to change a variable the condition does not use. In the following loop,
totalchanges, but the condition checkscount, so the loop never ends:Update the variable that the condition checks, in this case
count.
Practice¶
- Set
n = 10. Use awhileloop to subtract 3 fromneach round whilenis greater than 0. Assert that the final value ofnis -2. - Set
x = 3. Use awhileloop to doublexuntil it is at least 50. Assert thatxis 96. - Use a
whileloop to count how many times you can halve 1000 with//before it reaches 0. Store the count instepsand assert thatstepsis 10. - Set
number = 1andtotal = 0. Use awhileloop to add the odd numbers 1, 3, 5, 7, and 9 tototal. Assert thattotalis 25. - Stretch: start with
power = 1anddoublings = 0. Use awhileloop to doublepowerwhile it is at most 1000, and count the doublings. Assert thatpoweris 1024 anddoublingsis 10.
Solution
-
python n = 10 while n > 0: n -= 3 assert n == -2 -
python x = 3 while x < 50: x = x * 2 assert x == 96 -
python n = 1000 steps = 0 while n > 0: n = n // 2 steps += 1 assert steps == 10 -
python number = 1 total = 0 while number <= 9: total += number number += 2 assert total == 25 -
python power = 1 doublings = 0 while power <= 1000: power = power * 2 doublings += 1 assert power == 1024 assert doublings == 10
Recap¶
- A
whileloop checks its condition before each round and runs the block while the condition isTrue. - The block must change a variable that the condition depends on. Otherwise the loop never ends.
+=adds to a variable in place. A counter is a variable that changes each round.