Control FlowBeginner8 min29 / 63

while Loops

Learn how to repeat code for as long as a condition is true, avoid infinite loops, and use break to exit early.

Imagine you are filling a glass of water. You keep pouring while the glass is not full. The moment it fills up, you stop. That is exactly how a while loop works in Python.

A while loop runs a block of code over and over again as long as a condition stays True. The moment the condition becomes False, Python stops and moves on.

See it in action

Visual walkthrough1 / 5
1

Repeat Until You Say Stop

A while loop runs a block of code over and over as long as a condition stays True. Think of pouring water into a glass — you keep pouring while it isn't full.

while loops are perfect when you don't know in advance how many times you'll need to repeat.

#The Basic Shape

This loop prints 'Hello!' three times, then stops.
count = 1

while count <= 3:
    print("Hello!", count)
    count = count + 1

print("Done!")

Let's break down what is happening step by step: - count = 1 — we start a counter at 1. - while count <= 3 — Python checks: is count less than or equal to 3? If yes, run the indented block. - print(...) — prints the message. - count = count + 1 — we increase the counter by 1. This is the crucial step that moves us closer to stopping. - After each pass, Python goes back to the while line and checks again. When count reaches 4, the condition is False and the loop ends.

#The Counter Pattern

Using a variable to count loop iterations is called the counter pattern. It is one of the most common patterns in programming. You need three things: - Initialize the counter before the loop (count = 1) - Check the counter in the condition (while count <= 5) - Update the counter inside the loop (count = count + 1)

A shortcut for count = count + 1 is count += 1. They do the same thing.

Using += 1 as a shorter way to increase the counter.
count = 1

while count <= 5:
    print(count)
    count += 1

#The Danger: Infinite Loops

Watch out

Infinite Loop Ahead!

If your condition never becomes False, the loop runs forever. Your program will freeze. This is called an infinite loop and it is the most common mistake with while loops.

Example of an infinite loop — do not run this: ``python count = 1 while count <= 5: print(count) # Oops! We forgot count += 1 ` Because count never changes, count <= 5 is always True. Python prints 1` forever.

The fix: always make sure something inside the loop moves you closer to the condition being False.

Tip

How to Stop an Infinite Loop

If your program ever gets stuck in an infinite loop, press Ctrl + C in your terminal. This sends a "stop" signal to Python and breaks out of the loop.

#Exiting Early with break

Sometimes you want to stop a loop in the middle based on something that happens inside it. The break statement does exactly that — it immediately exits the loop, no matter what the condition says.

break jumps out of the loop the moment count hits 4.
count = 1

while count <= 10:
    if count == 4:
        print("Found 4, stopping!")
        break
    print(count)
    count += 1
Think of it like

break is Like an Emergency Exit

Think of a while loop as a hallway you keep walking through in circles. The condition at the start is the normal door — you stop when it closes. break is the emergency exit in the middle of the hallway. You can use it to leave immediately without waiting for the normal exit.

#Classic Use: Asking Until the Answer is Valid

One of the most practical uses of while is input validation — keep asking the user for input until they give you something acceptable. This pattern is everywhere: login forms, menus, prompts that need a number.

The loop keeps asking until the user types 'yes' or 'no'.
answer = ""

while answer != "yes" and answer != "no":
    answer = input("Please type yes or no: ")

print("You said:", answer)
Using 'while True' with break is a clean pattern for input loops.
while True:
    name = input("Enter your name (cannot be empty): ")
    if name != "":
        break
    print("Name cannot be empty. Try again.")

print("Hello,", name + "!")

while True creates a loop that would run forever on its own — but we control exactly when it stops by using break. This is a very common and readable pattern for "keep going until I say stop."

#for vs while: Which One to Use?

Note

Choosing Between for and while

Both loops repeat code, but they suit different situations:

  • Use `for` when you know exactly how many times to loop, or when you are going through a list or sequence.
  • Use `while` when you want to repeat until something changes — especially when you do not know in advance how many times that will be.

Examples: - Printing numbers 1 to 10 → for (you know it is 10 times) - Asking for input until it is valid → while (you don't know how many tries it will take)

Common mistake

Off-by-One Errors

A sneaky beginner mistake is getting the condition slightly wrong and looping one too many (or one too few) times.

``python count = 1 while count < 3: # stops at 2, not 3! print(count) count += 1 ``

Output: 1 then 2 — not 1 2 3. When you want to include the last number, use <= instead of <.

Quick check

What will this code print? ```python x = 5 while x > 0: print(x) x -= 2 ```

Key takeaways

  • A `while` loop repeats as long as its condition is `True` — it stops the moment the condition becomes `False`.
  • Always update something inside the loop so the condition can eventually become `False`, or you risk an infinite loop.
  • Use `break` to exit a loop immediately from the inside — great for input validation with `while True`.
  • Choose `for` when you know the number of iterations; choose `while` when you repeat until something changes.
  • Press Ctrl + C to escape an infinite loop that freezes your program.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
x = 5
while x > 0:
    print(x)
    x -= 2
Fix the bug#2

This code is supposed to print the numbers 1, 2, and 3, then print 'Done!'. What is wrong?

fix-bug
count = 1

while count <= 3:
    print(count)

print("Done!")
Fill in the blank#3

Complete the code so it counts from 1 to 4, printing each number, using the += shortcut.

count = 1

while count  4:
    print(count)
    count  1
Reorder the lines#4

Put these lines in the right order so the program counts down from 3 to 1, then prints 'Blastoff!'

1
print("Blastoff!")
2
    count -= 1
3
while count > 0:
4
    print(count)
5
count = 3
Your turn
Practice exercise

Write a program that counts down from 10 to 1 using a while loop, printing each number on its own line. After the countdown, print 'Blastoff!'

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable