Repeat while a test holds
while repeats as long as its test stays true. Use it when you don't know in advance how many passes it takes.
- Write a while loop whose test is checked before every pass
- Change the value the test depends on, so the loop can end
- Read typed lines in a loop until a stop value arrives
for repeats once per character, so the number of passes is known before it starts. Many repeats aren't like that. *How many weeks until I've saved enough? Ask again until the PIN is right. Keep reading quantities until the packer types 0.* You only know when to stop once you get there.
while test: checks the test. If it is true, Python runs the indented lines, then goes back and checks the test again. The first time the test is false, the loop ends and the next line at the left edge runs.
A new shorthand helps here. weeks += 1 means weeks = weeks + 1, and saved += 40 means saved = saved + 40. -= and *= work the same way.
Run each example to see what it prints. Running examples doesn't count toward progress.
saved = 0 weeks = 0 while saved < 250: saved += 40 weeks += 1 print("Weeks:", weeks) print("Saved:", saved)
The same shape works with typed lines: ask once before the loop, and ask again at the end of each pass. The test then looks at the newest answer.
pin = input("PIN? ") tries = 1 while pin != "2580": print("Wrong PIN") pin = input("PIN? ") tries += 1 print("Unlocked after", tries, "tries")
When to use it: for when you are walking a text or counting a known number of times; while when the stop depends on something that happens during the loop.
Mistakes to avoid:
- Never changing what the test looks at. If
savednever grows,saved < 250stays true forever and the program never finishes. (Check stops a program that runs too long.) - The off-by-one test:
<and<=differ exactly at the goal. Decide whether reaching the goal is enough. - Reading input only once, before the loop. The test then keeps looking at the same old answer.
- while test: checks the test before every pass and stops the first time it is false.
- Something inside the loop must change what the test looks at; with input, read again at the end of each pass.
- x += 1 is short for x = x + 1. Next: range for counting, and enumerate for positions.