Python Basics

Python While Loop with Examples

Keep repeating until something changes: a countdown, a menu or a retry loop.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • How the while condition is checked
  • Updating the variable that ends the loop
  • break, continue and avoiding infinite loops
count = 3
  1. 1count > 0Check the condition
  2. 2print(count)Run the body
  3. 3count -= 1Move toward the end
↺ back to the check: prints 3, 2, 1, then stops

Repeat while the condition is True

The problem

Some tasks repeat until something happens, and you cannot know in advance how many rounds that takes: ask for a password until it is correct, keep rolling a dice until you get a six, count down until zero. A for loop needs a known list; these tasks need a loop that checks a condition.

Think of it like this

A while loop is like stirring soup until it boils. You do not count stirs in advance. Before each stir you check: is it boiling yet? As long as the answer is no, you keep stirring. Something must change, or you would stir forever.

From stirring soup to code
countdown = 3🍲 Start: the soup is cold
while countdown > 0:❓ Check before each round: keep going?
countdown -= 1🥄 Each round changes something
print("Go!")✅ Condition false: move on
The condition is checked before every round; the loop stops when it becomes False.
In one sentence

A while loop repeats its block as long as its condition is True, checking the condition again before every round.

Key points

  1. while countdown > 0: checks the condition first; if it is already False, the block never runs.
  2. countdown -= 1 changes the value every round, so the condition eventually becomes False.
  3. Without that change the loop would run forever, and you would have to stop the program by hand.
  4. After the loop, the program continues with the next line, here print("Go!").

When should you use it?

  • Asking for input until it is valid, such as a menu choice or a password.
  • Games and simulations that run until someone wins or time runs out.
  • Repeating until a calculation is close enough, such as halving a number until it is below 1.

When not to use it

  • Going through every item of a list: a for loop is simpler and cannot loop forever.
  • Repeating a fixed number of times: for _ in range(10): says that more clearly.

See how it works

Press Step to run the while loop one move at a time. The condition is checked before every pass, and the loop stops as soon as it is false.

Example code

Run code →
main.py
countdown = 3

while countdown > 0:
    print(countdown)
    countdown -= 1

print("Go!")
Get a Run button for this example

Result of running the code

3
2
1
Go!

Code explanation

The counter changes during every iteration. Without that update, the condition would remain true and create an infinite loop.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Python while loop patterns

while count > 0:Repeat as long as the condition is true
count -= 1Update the variable the condition depends on
while True: ... breakLoop until something inside decides to stop
continueSkip the rest of this pass and check the condition again
while items:Loop while a list still has items
while ... else:The else block runs when the condition becomes false (not after break)
while (line := f.readline()):Assign and test in one step (Python 3.8+)

Common mistakes with Python while loops

Never updating the condition

If nothing inside the loop changes the condition, the loop runs forever.

Problem
count = 3
while count > 0:
    print(count)  # prints 3 forever
Fix
count = 3
while count > 0:
    print(count)
    count -= 1

continue before the update

continue jumps back to the condition, so an update placed after it is skipped and the loop can get stuck.

Problem
n = 0
while n < 5:
    if n == 2:
        continue  # n stays 2 forever
    print(n)
    n += 1
Fix
n = 0
while n < 5:
    n += 1
    if n == 3:
        continue
    print(n)  # 1, 2, 4, 5

Using while where a for loop is clearer

When you know the number of steps, a for loop with range() cannot forget the update.

Problem
i = 0
while i < 3:
    print(i)
    i += 1
Fix
for i in range(3):
    print(i)

Frequently asked questions

What is the difference between a while loop and a for loop?

A for loop runs once per item in a sequence and stops by itself. A while loop runs as long as a condition is true, which suits cases where the number of steps is not known in advance, such as reading input until the user types quit.

How do I stop an infinite while loop?

Make sure the loop changes its condition, or use break when a stop condition is met. In a terminal, Ctrl+C interrupts a running program.

What does while True mean?

It starts a loop that only ends with break (or return). It is a common pattern for menus and input loops where the exit is decided inside the loop.

Does Python have a do-while loop?

No. Use while True: with the body first and if condition: break at the end, so the body always runs at least once.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges