Lesson 14 of 30 · Loops
While Loops
Learn Python while loops: repeat code as long as a condition is true, avoid infinite loops and know when to choose while instead of for.
- 6 min read
- Beginner
- Reviewed
- How a while loop repeats code as long as a condition is true
- The three parts every while loop needs
- What an infinite loop is and how to avoid one
- When to use while and when to use for
Repeat until something changes
A for loop is perfect when you know what to loop over. But sometimes you do not know how many times you need to repeat. Keep asking until the password is correct. Keep halving a number until it is small enough. Keep training until the model is accurate.
A while loop repeats its block as long as a condition is True.
count = 1
while count <= 5:
print("Count is", count)
count += 1
print("Loop finished.")Before every pass, Python checks the condition count <= 5. If it is True, the block runs. If it is False, the loop ends.
The three parts of a while loop
Every working while loop has three parts. Find them in the example above.
- A starting value, set before the loop:
count = 1 - A condition that is checked before each pass:
count <= 5 - A change inside the loop that will eventually make the condition false:
count += 1
Infinite loops
If you forget the third part, the condition stays True for ever. This is called an infinite loop.
count = 1
while count <= 5:
print("Count is", count) # count never changes, so this never stopsWhen you cannot predict the number of passes
This is where while really earns its place. How many times can you halve 100 before it drops below 1? You do not need to know. The loop finds out.
number = 100
steps = 0
while number >= 1:
number = number / 2
steps += 1
print("It took", steps, "halvings.")A while loop with user input
A classic use is to keep asking until the answer is acceptable. The Input box below holds three attempts, one per line.
password = input("Password: ")
while password != "python":
print("Wrong password. Try again.")
password = input("Password: ")
print("Welcome!")Notice that input() appears twice: once before the loop to get the first attempt, and once inside it to get the next one. That second call is the change that lets the loop end.
for or while?
Use for when... | Use while when... |
|---|---|
| You have a list, string or range to go through | You repeat until a condition changes |
| You know the number of repetitions | You cannot know the number in advance |
| Example: print every name in a list | Example: ask until the input is valid |
If both would work, choose for. It is shorter and cannot loop for ever.
Common mistakes
Write a while loop that counts down from 3 to 1, then prints Liftoff!.
countdown = 3 # Use a while loop to print 3, 2, 1 on separate lines, # then print Liftoff! after the loop.
What happens if the condition of a while loop never becomes False?
Summary
while condition:repeats its block as long as the condition isTrue.- A
whileloop needs a starting value, a condition and a change. - Forgetting the change causes an infinite loop.
- Use
forto go through a collection, andwhileto repeat until something happens.
Next: two keywords that give you finer control over any loop.
Finished reading? Tick it off to track your progress.