The while Loop in Python
A while loop repeats a block of code as long as a condition is true. Python checks the condition before every pass and leaves the loop the first time it is false. That makes a while loop the right tool when you only know when to stop, not what to loop over.
Key facts
while condition:checks the condition before every pass. If it is false the first time, the block never runs.- Something has to make the condition false, usually a line inside the block, or a
breakhas to end the loop. breakends a while loop early, andwhile True:with abreakis how Python writes a do-while loop.- Use a for loop when you know what to loop over, and a while loop when you only know when to stop.
What is a while loop in Python?
A while loop is a loop controlled by a condition instead of a sequence. The header is while, a condition and a colon, and the indented block under it runs again and again until the condition becomes false.
count = 1
while count <= 3:
print("Pass", count)
count = count + 1
print("Finished")Pass 1 Pass 2 Pass 3 Finished
count is the counter. The last line of the block moves it one step closer to the end, and the condition fails on the fourth check, when count is 4, so the loop ends and Finished prints.
How does a while loop check its condition?
Python checks the condition before every pass, including the first. When it is true the block runs, then Python jumps back to the top and checks again. If the condition is false on the first check, the block runs zero times.
n = 10
while n < 5:
print("This never prints")
print("n is", n)n is 10
The condition n < 5 is false on the first check, so the block is skipped. The next example halves a number until it drops below 1, a job where the number of passes isn't known in advance.
number = 100
steps = 0
while number >= 1:
number = number / 2
steps = steps + 1
print(steps)
print(number)7 0.78125
It took seven halvings to get below 1, and the last line shows what was left of the number.
How do I stop a while loop?
Make the condition false, or leave the loop with break. The usual way is a variable in the condition that the block changes, such as a counter or the reply from input().
reply = ""
while reply != "quit":
reply = input("Type quit to stop: ")
print("You typed", reply)
print("Bye")Type quit to stop: You typed hello Type quit to stop: You typed quit Bye
The line reply = "" gives the first check something to compare. The input box holds two lines, and each input() call takes the next one. The two answers show up only in the You typed lines, because the output panel doesn't echo input the way a terminal does.
break leaves a loop at once, whatever the condition says, and the break and continue lesson covers it in full.
count = 0
while count < 100:
count = count + 1
if count == 3:
break
print(count)3
What is an infinite loop in Python?
An infinite loop is a loop that never ends. In a while loop, that happens when the condition never becomes false and no break runs.
The usual cause is a block that never changes the variable in the condition. In a terminal, Ctrl+C stops the program, and a lesson example stops when you press Stop or after 15 seconds.
count = 10
while count > 0:
total = count * 2
print("Done")Stopped after 15 seconds because the program took too long.
Nothing in the block touches count, so count > 0 stays true forever and print("Done") never runs. Add count = count - 1 to the block and the loop ends after ten passes.
What is while True used for?
while True: is for a loop whose exit test sits in the middle of the block. A common case is reading input and checking it before doing anything else. The loop's condition never fails, so a break is what normally ends it.
isdigit() returns True when the text holds nothing but digits, so even -5 and 4.5 fail it.
while True:
text = input("Enter a whole number: ")
if text.isdigit():
break
print("Not a number, try again")
print("Thanks, you entered", int(text))Enter a whole number: Not a number, try again Enter a whole number: Thanks, you entered 42
The first reply, abc, fails the digit test, so the loop asks again. The second reply, 42, passes it, and the break ends the loop.
Does Python have a do-while loop?
No. Python has no do-while statement, so a loop that must run at least once is written as while True: with the check at the end of the block and a break when it passes.
total = 0
while True:
total = total + 7
print(total)
if total >= 20:
break7 14 21
The block runs before the check, which is what do-while means in C and JavaScript. If total started at 25, a loop with the check at the top would print nothing, while this one still prints once.
Can a while loop have two conditions?
Yes. Join the two conditions with and or or, which the logical operators lesson covers. With and, the loop continues only while both are true, so it stops as soon as either one fails.
balance = 50
days = 0
while balance > 0 and days < 5:
balance = balance - 20
days = days + 1
print(days, balance)3 -10
The balance drops to 30, then 10, then -10, and on the fourth check balance > 0 is false, so the loop stops after three days even though days < 5 still holds.
Should I use a for loop or a while loop?
Pick the for loop when you know what to loop over. Pick the while loop when you only know when to stop. Each can do the other's job, but the natural choice reads better and is harder to get wrong.
| Loop | Use it when | How it ends | Example header |
|---|---|---|---|
for | You have a sequence or a known number of passes | The sequence runs out, or break runs | for n in range(10): |
while | You only know the condition for stopping | The condition becomes false, or break runs | while balance > 0: |
for n in range(1, 4):
print(n)
n = 1
while n <= 3:
print(n)
n = n + 11 2 3 1 2 3
Both loops print the same three numbers. The for version needs no counter and can't forget to update one, which is why counting is a job for the for loop.
Common mistakes with while loops in Python
Two of these four mistakes stop the program with a message. The other two make the loop run forever or not at all.
- Forgetting to update the counter. The condition never changes and the loop runs forever. Make sure a line in the block moves the variable toward the end.
- SyntaxError: expected ':'. The colon after the condition is missing.
- TypeError: '<' not supported between instances of 'str' and 'int'.
input()returns text, so a condition such aswhile guess < 10:fails until you convert the reply withint(). - A condition that is false from the start.
while count > 0:withcountat 0 runs zero times and prints nothing, and no error points at it.
Run both broken programs to see the messages, then fix them in the editor. In the second one, change "5" to 5 and the loop prints Too low five times.
count = 1
while count <= 3
print(count)
count = count + 1 File "main.py", line 2
while count <= 3
^
SyntaxError: expected ':'guess = "5"
while guess < 10:
print("Too low")
guess = guess + 1Traceback (most recent call last):
File "main.py", line 2, in <module>
while guess < 10:
^^^^^^^^^^
TypeError: '<' not supported between instances of 'str' and 'int'Exercise
Fix the condition so the program prints 5 down to 1 on separate lines and then Liftoff! on the last line. The starter stops one number early and never prints the 1.
count = 5
while count > 1:
print(count)
count = count - 1
print("Liftoff!")
5 4 3 2 1 Liftoff!
Show the solution
count = 5
while count > 0:
print(count)
count = count - 1
print("Liftoff!")
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
i = 0 while i < 3: i = i + 1 print(i)The loop adds 1 until i reaches 3, and the print sits after the loop, so only the final value prints. Indenting print(i) into the block, under the addition, would show 1, 2 and 3.
-
2What does this program print?
n = 5 while n < 5: print("hi") print("done")n < 5 is false on the first check, so the block never runs and only done prints. A while loop can run zero times.
-
3What is missing from this loop, which prints 1 forever?
count = 1 while count <= 3: print(count)Nothing in the block changes count, so count <= 3 stays true and the loop never ends. The colon and the indent are already there, and Python does not need parentheses around a condition.
-
4What does this program print?
x = 1 while x < 100 and x != 8: x = x * 2 print(x)x doubles to 2, 4 and then 8, and the combined condition fails as soon as x equals 8. The x < 100 part never gets the chance to stop the loop.
-
5What happens when a while True loop has no break inside it?
The condition True never becomes false, so without a break the loop keeps going until something else, such as an error or Ctrl+C, stops it. The loop is valid Python, so it is not a syntax error.























