Python while Loops Explained

A while loop repeats a block for as long as a condition stays true. Learn the syntax, the while True pattern, how to validate input, and how to avoid infinite loops.

4 min read

A Python while loop repeats a block of code for as long as its condition is true. Python checks the condition before every pass and leaves the loop as soon as the condition is false.

pythonpython
count = 1
 
while count <= 3:
    print(count)
    count += 1
 
print("Done")

This prints 1, 2, 3, and then Done. When count reaches 4, the condition count <= 3 is false, so Python skips the block and continues with the line after the loop.

The syntax

pythonpython
while condition:
    # block to repeat

A working while loop almost always has three parts:

  1. A starting value set before the loop (count = 1).
  2. A condition that is checked before each pass (count <= 3).
  3. An update inside the block that moves towards ending the loop (count += 1).

If the condition is false the very first time, the block never runs at all.

When to use while instead of for

Use a for loop when you are going through a collection or know the number of repetitions. Use a while loop when you cannot know how many passes you need:

  • Keep asking until the user enters valid input.
  • Keep reading until a file or network stream is finished.
  • Run a game or menu until the player quits.
  • Repeat a calculation until the result is close enough.
pythonpython
# How many years until savings double at 5% interest?
balance = 1000
years = 0
 
while balance < 2000:
    balance *= 1.05
    years += 1
 
print(years)  # 15

There is no list to loop over here. The loop simply runs until the goal is reached.

Avoid infinite loops

If nothing inside the block changes the condition, the loop never ends:

pythonpython
count = 1
 
while count <= 3:
    print(count)
    # count += 1 is missing, so this prints 1 forever

To stop a program that is stuck in a loop, click in the terminal and press Ctrl+C. Python stops with a KeyboardInterrupt message.

When a loop will not stop, check three things: that the update line exists, that it is indented inside the loop, and that it moves the variable in the right direction.

while True with break

Sometimes the natural place to decide whether to stop is in the middle of the block. The usual pattern is an intentionally endless loop with a break:

pythonpython
while True:
    command = input("Type a command (or quit): ")
    if command == "quit":
        break
    print("You typed:", command)
 
print("Goodbye")

while True never becomes false, so the only way out is the break statement. This avoids asking for input in two places, once before the loop and once inside it.

Python has no do while loop. while True with a break at the end of the block is how you write a loop that must run at least once.

Validate user input

A while loop is the standard way to ask again until the input is acceptable:

pythonpython
while True:
    answer = input("Enter your age: ")
    if answer.isdigit() and int(answer) > 0:
        age = int(answer)
        break
    print("Please enter a whole number above zero.")
 
print("Your age is", age)

str.isdigit() checks that the text contains only digits, so the conversion with int() cannot fail. More on reading input is in getting user input in Python.

Loop until a collection is empty

An empty list counts as false, so a list can be the condition itself:

pythonpython
queue = ["email", "report", "backup"]
 
while queue:
    task = queue.pop(0)
    print("Processing", task)
 
print("All tasks done")

Each pass removes the first task. When the list is empty, the loop ends.

The else clause

Like a for loop, a while loop can have an else block. It runs when the condition becomes false, but not when the loop is left with break:

pythonpython
attempts = 0
 
while attempts < 3:
    guess = input("Password: ")
    if guess == "open sesame":
        print("Access granted.")
        break
    attempts += 1
else:
    print("Too many attempts.")

Common mistakes

MistakeWhat happensFix
No update inside the loopInfinite loopChange the condition variable in the block
Update line not indentedInfinite loopIndent it to the level of the block
Using < where <= is neededThe loop runs one time too fewTrace the first and last pass by hand
Comparing input() text with a numberThe condition is never trueConvert with int() or float() first
Using while to walk a list by indexExtra code and off-by-one bugsUse a for loop
Rune AI

Rune AI

Key Insights

  • A while loop repeats its block for as long as the condition is true and checks the condition before every pass.
  • Most while loops need a starting value, a condition, and an update that moves towards ending the loop.
  • A loop with no update never ends; press Ctrl+C to stop it.
  • Use while True with break when the exit decision belongs in the middle of the block.
  • Python has no do while loop; while True with break covers that case.
  • Prefer a for loop when you are going through a collection.
RunePowered by Rune AI

Frequently Asked Questions

What is a while loop in Python?

A while loop repeats a block of code for as long as a condition is true. Python checks the condition before each pass and exits the loop the first time the condition is false.

What is the difference between for and while in Python?

A for loop runs once for each item in a collection or range, so it is the choice when you know what you are looping over. A while loop runs until a condition changes, so it suits situations where the number of passes is not known in advance.

How do I stop a while loop in Python?

Make the condition false, or use break to leave the loop immediately. If a running program is stuck in a loop, press Ctrl+C in the terminal.

Does Python have a do while loop?

No. Write while True: and put an if with break at the point where the loop should end. The block then always runs at least once, which is what a do while loop does in other languages.

What does while True mean in Python?

while True starts a loop whose condition never becomes false, so it repeats until a break statement, a return, or an error ends it. It is common for menus, input validation, and programs that run until the user quits.

Conclusion

Use a while loop when repetition depends on a condition rather than on a collection. Set a starting value, check a condition, and make sure something in the block moves towards ending the loop. For input and menus, while True with a break is the clearest pattern.