Learn

Short lessons with real code you can edit and run on the page.

The while Loop in Python

Lesson 14 Python 3.14 Runs in your browser
In short

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 break has to end the loop.
  • break ends a while loop early, and while True: with a break is 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.

Python
count = 1
while count <= 3:
    print("Pass", count)
    count = count + 1
print("Finished")
Output
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.

Python
n = 10
while n < 5:
    print("This never prints")
print("n is", n)
Output
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.

Python
number = 100
steps = 0
while number >= 1:
    number = number / 2
    steps = steps + 1
print(steps)
print(number)
Output
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().

Python
reply = ""
while reply != "quit":
    reply = input("Type quit to stop: ")
    print("You typed", reply)
print("Bye")
Output
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.

Python
count = 0
while count < 100:
    count = count + 1
    if count == 3:
        break
print(count)
Output
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.

Python
count = 10
while count > 0:
    total = count * 2
print("Done")
Output
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.

Python
while True:
    text = input("Enter a whole number: ")
    if text.isdigit():
        break
    print("Not a number, try again")
print("Thanks, you entered", int(text))
Output
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.

Python
total = 0
while True:
    total = total + 7
    print(total)
    if total >= 20:
        break
Output
7
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.

Python
balance = 50
days = 0
while balance > 0 and days < 5:
    balance = balance - 20
    days = days + 1
print(days, balance)
Output
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.

Python for loop compared with while loop
LoopUse it whenHow it endsExample header
forYou have a sequence or a known number of passesThe sequence runs out, or break runsfor n in range(10):
whileYou only know the condition for stoppingThe condition becomes false, or break runswhile balance > 0:
Python
for n in range(1, 4):
    print(n)
n = 1
while n <= 3:
    print(n)
    n = n + 1
Output
1
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 as while guess < 10: fails until you convert the reply with int().
  • A condition that is false from the start. while count > 0: with count at 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.

Python
count = 1
while count <= 3
    print(count)
    count = count + 1
Output
  File "main.py", line 2
    while count <= 3
                    ^
SyntaxError: expected ':'
Python
guess = "5"
while guess < 10:
    print("Too low")
    guess = guess + 1
Output
Traceback (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.

Python
count = 5
while count > 1:
    print(count)
    count = count - 1
print("Liftoff!")
Output
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.

  1. 1What does this program print?

    i = 0
    while i < 3:
        i = i + 1
    print(i)
  2. 2What does this program print?

    n = 5
    while n < 5:
        print("hi")
    print("done")
  3. 3What is missing from this loop, which prints 1 forever?

    count = 1
    while count <= 3:
        print(count)
  4. 4What does this program print?

    x = 1
    while x < 100 and x != 8:
        x = x * 2
    print(x)
  5. 5What happens when a while True loop has no break inside it?

Frequently asked questions

What is the difference between a for loop and a while loop in Python?
A for loop runs once per item in a sequence, and a while loop runs while a condition holds. Use a for loop when you know what to loop over and a while loop when you only know when to stop.
Does Python have a do-while loop?
No. Write while True with the check at the end of the block and a break when it passes. The block then runs at least once, which is what do-while does in C and JavaScript.
How do I stop an infinite loop in Python?
Press Ctrl+C in the terminal, which raises KeyboardInterrupt and ends the program. To keep it from happening again, add a line inside the loop that changes the variable in the condition.
Can a while loop run zero times?
Yes. Python checks the condition before the first pass, so a condition that is false at the start skips the block entirely.
How do I write a while loop with two conditions in Python?
Join the two conditions with and when both must hold, or with or when either one is enough. For example, while balance > 0 and days < 5 stops the first time either part is false.
What does while True mean in Python?
while True starts a loop whose condition is always true. It runs until something ends it, usually a break, an error or Ctrl+C, and it is the standard way to write a loop whose exit test belongs in the middle of the block.