What is a while loop?
Loops are one of the fundamental constructs that let us control the flow of a program. A while loop repeats a block of code while a specific condition is true. That makes while loops perfect for when you want to repeat code an unknown number of times.
You actually use while loops in everyday life all the time:
- While the road is straight, drive forward.
- While the temperature is at or below 68 degrees, keep the heat on.
In both examples, you don't know ahead of time when the road will curve or when the temperature will change. You just keep going until the condition stops being true.
A while loop in Python looks like this:
while condition: # code to execute # while the condition is true
Here is the whole trick in two sentences. If the condition evaluates to True, the code inside the loop runs, then Python jumps back up and checks the condition again. Once the condition evaluates to False, the computer exits the loop and continues on with the rest of the program.
Remember the rhythm: check the condition, run the body, check the condition, run the body... and the moment the check comes back False, the loop is over.
While loop vs. for loop
If you've met the for loop, you might wonder why Python needs two kinds of loops. They both repeat code, but they answer different questions:
for loop
"Repeat this a known number of times."
- You know the count up front: range(10) means exactly 10 times
- Great for counting, or visiting every item in a string or list
- Python updates the loop variable for you
while loop
"Repeat this until something changes."
- You don't know the count: it runs while a condition stays true
- Great for games, user input, and waiting for something to happen
- You are in charge of changing the condition variable
Quick test: "Print hello 100 times" is a for loop job. "Keep asking for a password until it's correct" is a while loop job, because you have no idea how many tries it will take!
The Loop Machine
The best way to understand a while loop is to watch the computer re-check the condition on every lap. Pick a program, then press Step to move one moment at a time. Watch the condition box: every single loop starts with a fresh True or False check.
Try the Infinite loop! program last. It looks almost identical to the taco countdown, but one missing line changes everything.
Example: the taco countdown
Look at the example program below. In plain English, it says: while there are more than 0 tacos, eat a taco. Press Run, then explore with these guiding questions:
- What happens if you change the initial value of num_tacos?
- What happens if you change the condition to num_tacos < 0?
- When does the final print statement run? Why does it run at that moment?
- What happens if you change the while loop to an if statement?
num_tacos = 5 while num_tacos > 0: print("I ate one delicious taco!") num_tacos = num_tacos - 1 # print out how many tacos are left print("There are " + str(num_tacos) + " left.") print("Looks like we need to make some more tacos!")
I ate one delicious taco! There are 4 left. I ate one delicious taco! There are 3 left. I ate one delicious taco! There are 2 left. I ate one delicious taco! There are 1 left. I ate one delicious taco! There are 0 left. Looks like we need to make some more tacos!
The line that matters most: num_tacos = num_tacos - 1. Every lap, the loop changes the variable in its own condition. That's what guarantees the condition eventually becomes False so the loop can end.
Looping on user input: the guessing game
Here's where while loops really shine. This guessing game keeps asking the player for a guess until they find the secret number. Nobody, not even the programmer, knows how many guesses it will take. A for loop can't do that!
Before running the program, predict what you think will happen. What is the while loop condition in plain English? When will the loop end? (If the != symbol is new to you, it means "not equal to". Check out the Booleans and Logical Operators tutorial for more.)
import random secret_num = random.randint(1, 10) guess = "" while guess != secret_num: guess = int(input("Guess a number between 0 and 10: ")) print("Great job! You guessed the random number!")
Guess a number between 0 and 10: 3 Guess a number between 0 and 10: 9 Guess a number between 0 and 10: 7 Great job! You guessed the random number!
Notice the condition: guess != secret_num. In plain English, it says "keep looping while the guess is not the secret number." The player's correct guess is what finally flips the condition to False. A special value that ends a loop like this is often called a sentinel value: the loop stands guard until it shows up.
Why start with guess = ""? The condition gets checked before the first lap, so guess needs some starting value. An empty string can never equal the secret number, so the loop is guaranteed to run at least once and ask for a guess.
Infinite loops
When writing a while loop, beware of the infinite loop! An infinite loop happens when the condition is always true. The computer will try to run the loop forever, which ultimately crashes the browser or causes an error.
Let's revise our tacos program slightly. Look closely. Can you figure out why this program results in an infinite loop?
num_tacos = 5 while num_tacos > 0: print("There are " + str(num_tacos) + " left.")
There are 5 left. There are 5 left. There are 5 left. There are 5 left. There are 5 left. There are 5 left. ... this would repeat forever! (We stopped it for you.)
Spot the problem? We never change the value of num_tacos inside the loop. That means num_tacos will always be 5, which means the condition num_tacos > 0 will always be True. The computer repeats the loop an infinite number of times because there is no way to exit.
How to avoid it: a big warning sign is a loop body that never changes the variable in the condition. Before you run a while loop, ask yourself: "What line inside this loop moves the condition closer to False?" If you can't point to one, you probably have an infinite loop on your hands.
Want to feel it happen safely? Open the Loop Machine above and pick the Infinite loop! program. The safety brake will kick in before your browser melts.
Practice with while loops
Practice your hand at while loops by completing any (or all!) of the following challenges.
Countdown from 10
Write a while loop that prints a countdown from 10. Remember to change the counting variable inside the loop, or you'll be counting down forever!
num = 10 while num > 0: print(num) num = num - 1 print("Liftoff!")
10 9 8 7 6 5 4 3 2 1 Liftoff!
The loop stops when num reaches 0, because 0 > 0 is False. The line num = num - 1 is what keeps this from becoming an infinite loop.
Countdown, your way
Write a program that goes from 100 to 0 at different intervals specified by the user. You can use the int(input("prompt")) command to get a number from the user. Your sample output might look like this:
Decrease by how much? 50 Number is now 50 Decrease by how much? 25 Number is now 25 Decrease by how much? 2 Number is now 23 Decrease by how much? 23 Number is now 0
number = 100 while number > 0: amount = int(input("Decrease by how much? ")) number = number - amount print("Number is now " + str(number))
This time the user controls how fast the condition moves toward False. That's exactly the kind of "unknown number of repeats" situation while loops are made for. Bonus challenge: what happens if the user's number takes number below 0? How would you handle that?
A while loop example
A while loop repeats as long as a condition is true. This program counts down from 5 and then counts up to 3.
Quick quiz
1. How many times does this loop print "hi"?
x = 0 while x < 3: print("hi") x = x + 1
2. What causes an infinite loop?
3. Which task is the best fit for a while loop instead of a for loop?
Keep learning Python
While loops repeat code as long as a condition is true. Next, learn how break and continue give you even finer control over your loops, or review how for loops handle the "known number of times" jobs.