SythraOpen app

The while Loop in Python

A while loop in Python repeats its body as long as a condition stays True, checking the condition before every pass — use break to exit early, and always make sure the body eventually makes the condition False.

Sythra

10 min read

XLinkedIn
The while Loop in Python — cover illustration

Recursion can repeat something — a function calling itself over and over until a base case stops it. That works, but it's not always the most natural way to think about plain repetition. The while loop in Python is a more direct tool for exactly this job.

Here is the countdown function, rewritten using while:

def countdown(n):
    while n > 0:
        print(n)
        n = n - 1
    print('Blastoff!')

You can almost read this like plain English: "While n is greater than 0, print n and subtract 1. Once n reaches 0, print Blastoff!" That readability is exactly what makes while so natural to write and to read.

What you will learn

  • Exactly what Python does on every pass through a while loop
  • Why an infinite loop happens, and how to spot one
  • How to exit a loop early with break
  • A real numerical example: computing square roots with Newton's method
  • Why comparing floats with == is dangerous inside a loop

What Python does, step by step

  1. Check the condition — is n > 0?
  2. If False — exit the loop completely and move on to whatever comes next.
  3. If True — run everything in the indented body, then jump back up to step 1.

This whole cycle is called a loop, because step 3 sends execution back around to the top, again and again.

# Infinite loop — do not actually run this
while True:
    print('Still going...')

Fun fact: the instructions on a shampoo bottle — "Lather, rinse, repeat" — have no stopping condition. Technically, that's an infinite loop.

A more interesting example: the Collatz sequence

def sequence(n):
    while n != 1:
        print(n, end=" ")
        if n % 2 == 0:
            n = n / 2        # even: divide by 2
        else:
            n = n * 3 + 1    # odd: multiply by 3, add 1

Try it with n = 3 and you get: 3, 10, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0. The sequence bounces around in a way that feels almost random, but it always seems to reach 1 eventually, no matter which starting number you pick.

The fascinating part? Nobody has ever proven that it always reaches 1 for every possible starting number — but nobody has ever found a number where it fails to, either. It's one of the most famous unsolved problems in all of mathematics, and you just implemented the whole thing in five lines of code.

break: walking out mid-loop

The while condition is only checked at the very top of each pass. But sometimes you don't actually know whether it's time to stop until you're already inside the body. For that, Python gives you break, which exits a loop immediately, from wherever you are inside it:

while True:
    line = input('> ')
    if line == 'done':
        break
    print(line)

print('Done!')

This loop runs forever by design — while True is always true. The only way out is break, which fires the moment the user types done. Here's what a run looks like:

> hello there
hello there
> not stopping yet
not stopping yet
> done
Done!

The pattern of while True: combined with a break somewhere inside is extremely common in real, professional programs. It lets you place your exit condition anywhere in the body, and phrase the condition in a positive, natural way — "stop when this happens" rather than the clunky, backwards "keep going for as long as that hasn't happened yet."

Square roots: looping toward the right answer

A genuinely beautiful real-world use of loops: computing square roots using Newton's method. The idea: start with any guess, then keep improving it using a formula, over and over, until the answer stops changing. The formula for a better estimate of √a, given your current estimate x, is:

y = (x + a / x) / 2

Watch how fast it converges for a = 4, starting from a rough guess of x = 3: round 1 gives 2.1666..., round 2 gives 2.0064..., round 3 gives 2.00001..., and by round 5 it has landed on 2.0. As an actual loop:

while True:
    y = (x + a / x) / 2
    if y == x:
        break
    x = y

The safe approach is to stop once the difference between them drops below some extremely tiny number, traditionally called epsilon:

epsilon = 0.0000001

while True:
    y = (x + a / x) / 2
    if abs(y - x) < epsilon:
        break
    x = y

When the two estimates land within 0.0000001 of one another, that's "close enough," and we stop. This is a general rule across all of numerical computing: never check decimal numbers for exact equality — always check that they're merely close together instead.

Common mistakes

  • Writing a condition that never becomes false, creating an accidental infinite loop
  • Forgetting to update the loop variable inside the body (e.g. missing n -= 1)
  • Comparing floats with == instead of checking they're within a small epsilon of each other
  • Using while when you already know exactly how many times to repeat — a for loop is usually clearer for that

Common questions

How does a while loop work in Python?

A while loop checks its condition; if True, it runs the indented body once and jumps back to check the condition again. This repeats until the condition becomes False, at which point the loop exits.

What causes an infinite loop in Python?

An infinite loop happens when the condition in a while statement never becomes False, usually because the loop body forgets to update the variable the condition depends on.

What does break do in a while loop?

break immediately exits the loop, no matter where it appears inside the body, without checking the condition again. It's commonly combined with while True: to place the exit condition anywhere inside the loop.

Why shouldn't I compare floats with == in a loop?

Floating-point numbers are stored only approximately in memory, so two mathematically equal values might differ by a tiny amount and never satisfy ==. Instead, check that the difference between them is smaller than a small threshold (epsilon).

When should I use while instead of for?

Use while when you don't know in advance how many times you'll repeat, and are waiting for a condition to change. Use for when you already know exactly what you're looping over, like a range of numbers or items in a list.

Explore

Related topics

Keep going — these sit next to this concept in a real learning path.

Browse all python explainers →