---
title: The while Loop in Python
source: https://app.sythra.ai/learn/python/while-loop-python
topic: Python
updated: 2026-08-12
publisher: Sythra (https://app.sythra.ai)
---

# 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.

_Source: [https://app.sythra.ai/learn/python/while-loop-python](https://app.sythra.ai/learn/python/while-loop-python) — free to read on Sythra._

## Key points

- while checks its condition before each pass, and stops the moment it's False
- The loop body must eventually change something so the condition can become False
- while True: with a break inside is a very common real-world pattern
- break exits a loop immediately, from anywhere inside its body
- Never compare floats with == inside a loop — check that they're within a small epsilon instead

[Recursion](/learn/python/recursion-in-python) 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`:

```python
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.

> **The golden rule of while loops:** 

```python
# 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

```python
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.

> **Worth noting:** 

## 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:

```python
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:

```text
> 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:

```python
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:

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

> **A subtle trap:** 

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

```python
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](/learn/python/for-loop-python) is usually clearer for that

> **Practice with Sythra:**  [Practice with AI tutor](https://app.sythra.ai/pricing)

## FAQ

### 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.

## Related

- [Prerequisites to Iteration in Python (Variable Updates)](https://app.sythra.ai/learn/python/prerequisites-to-iteration) — The variable update pattern every while loop relies on.
- [The for Loop in Python](https://app.sythra.ai/learn/python/for-loop-python) — Looping over ranges, strings, and lists with for.
- [The do-while Equivalent in Python (and Nested Loops)](https://app.sythra.ai/learn/python/do-while-python) — Simulating run-at-least-once loops and nesting loops.
- [Recursion in Python](https://app.sythra.ai/learn/python/recursion-in-python) — The other way to repeat — a function calling itself.
- [Python course hub](https://app.sythra.ai/learn/python) — All free Python explainers and the path into Agentic practice.
- [More Tools for Iteration in Python](https://app.sythra.ai/learn/python/iteration-tools-python) — continue, enumerate(), zip(), comprehensions, and generators.

---

Written by Sythra — Learn machine learning by building. Practice this topic with Sythra's AI tutor: https://app.sythra.ai/pricing
