while Loops
Laps around a running track: before every lap, the coach asks one question. "Done yet?" As long as the answer is no, you keep running.
Say you want to print the numbers 1 to 5. You could write five print lines. Now say you want 1 to 1,000. Or you want to keep asking a user for a password until they get it right, and you have no idea how many tries that will take.
Copying lines doesn't work anymore. You need a way to say "do this again, and again, until...". That's a loop. Python has two kinds, and this lesson covers the first: the while loop.
Laps around a track
Picture a coach timing you around a track. Before each lap, the coach checks one thing: "Have you done 5 yet?" If not, you run another lap, and the lap counter goes up by one. When the answer is yes, you stop.
Every while loop has those same three ingredients:
- A starting point, like the lap counter at zero.
- A condition that's checked before every lap. While it's
True, the loop keeps going. - A step that moves things forward, so the condition eventually becomes
False.
Forget the third one, and you'll be running laps forever. Programmers call that an infinite loop.
Your first while loop
lap = 1
while lap <= 5:
print("Lap", lap)
lap += 1
print("Done!")Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Done!The shape is just like an if from Making Decisions: a condition, a colon, and an indented block. The difference is what happens at the end of the block. An if runs its block once and moves on. A while jumps back up and checks the condition again.
Step by step:
lapstarts at 1.- Python checks
lap <= 5. It's true, so the block runs: it printsLap 1, andlapbecomes 2. - Back to the top.
2 <= 5is true, so it printsLap 2... - Eventually
lapis 6.6 <= 5is false, so the loop ends andDone!prints.
Each pass through the block is called an iteration. This loop has five.
If the condition is false from the very start, the block never runs at all. while 10 <= 5: would skip straight past.
Counting down, or by twos
The step doesn't have to be += 1:
count = 3
while count > 0:
print(count, "...")
count -= 1
print("Liftoff!")3 ...
2 ...
1 ...
Liftoff!n = 2
while n <= 10:
print(n, end=" ")
n += 22 4 6 8 10Running totals
A very common loop job is adding things up. Create a variable before the loop to hold the total, and add to it on every iteration:
total = 0
number = 1
while number <= 100:
total += number
number += 1
print("1 + 2 + ... + 100 =", total)1 + 2 + ... + 100 = 5050The total has to be created before the loop starts. Create it inside the loop, and it would be reset to 0 on every lap.
Repeating until something happens
Counting is the simplest use, but while really shines when you don't know how many times to repeat. You loop until something happens. How many years does it take for savings to reach a goal?
savings = 1000
years = 0
while savings < 2000:
savings = savings * 1.1
years += 1
print(f"It took {years} years to reach {savings:.2f}")It took 8 years to reach 2143.59Nobody told the loop to run 8 times. It kept going until the condition became false.
The same idea keeps asking the user until they give a valid answer:
age = int(input("Enter your age (1 to 120): "))
while age < 1 or age > 120:
print("That doesn't look right. Try again.")
age = int(input("Enter your age (1 to 120): "))
print("Thanks! You're", age)Enter your age (1 to 120): 200
That doesn't look right. Try again.
Enter your age (1 to 120): 17
Thanks! You're 17It asks once before the loop, and again at the end of each lap, until the answer is in range.
Two classic bugs
The infinite loop. Forget the step, and the condition never changes:
lap = 1
while lap <= 5:
print("Lap", lap)
# forgot lap += 1This prints Lap 1 forever. If it happens to you, don't panic: press Ctrl + C in the terminal to stop the program. Then check that something inside the loop moves it toward the end.
Off by one. The loop runs one time too many or one time too few. It's the most common loop bug of all:
n = 0
while n <= 5:
print(n, end=" ")
n += 10 1 2 3 4 5Six numbers, not five! When a loop runs the wrong number of times, check two things: where the counter starts (0 or 1?), and whether the condition uses < or <=. A useful habit is to trace a tiny case, like 3 iterations, by hand.
Try it
This program runs a countdown, adds up a class's savings week by week until they reach their goal, and reverses a word, one character at a time. Predict every line.
Running Python here
Running Python right in the browser is coming to Syntaxia soon. For now, you can read and edit the code here. If you have Python installed on your computer (see Setting Up), save it as main.py and run it with python main.py (or python3 main.py on macOS and Linux).
Check your prediction
3...
2...
1...
Go!
Reached 600 pesos after 4 weeks
LOOP backwards is POOL
Tries: 0The savings loop only checks the goal before each week, so the savings overshoot 500 and stop at 600. The word loop walks the index from 3 down to 0, adding one character at a time. And the last loop's condition is false from the start, so its block never runs at all.
Try it yourself
- Change the savings loop to save 120 pesos a week. How many weeks does it take now, and how much is saved?
- Write a
whileloop that prints the 7 times table, from7 x 1 = 7to7 x 10 = 70. - Write a loop that keeps asking "What is 6 x 7? " until the user types
42, then printsCorrect!.
Check your understanding
Up next
while loops are perfect when you don't know how many times to repeat. But when you do know, or when you want to go through every item in a collection, Python has a neater tool: for Loops and range().
