# Python while Loops: How They Work and When to Use Them

Source: https://devdocs10.com/articles/python/python-while-loops  
By Murat Bo · Published 2026-11-15 · DevDocs10 (https://devdocs10.com)

A `while` loop repeats code as long as a condition stays true. Use it when you do not know in advance how many times the loop should run, such as waiting for input, searching data, or repeating until a counter reaches a limit. This article shows the syntax, how the condition is checked, common mistakes, and how to avoid infinite loops.

> **Difficulty:** Beginner
>
> **Helpful to know first:** basic Python syntax, variables, Boolean values, and comparison operators like `<` and `==`.

## How Python while Loops Repeat Code

A `while` loop checks a condition before each repetition. If the condition is `True`, Python runs the loop body. If the condition is `False`, Python skips the body and moves on.

The smallest useful pattern looks like this:

```python
count = 0
while count < 3:
    print(count)
    count += 1

# Output:
# 0
# 1
# 2
```

Python starts with `count` equal to `0`. It checks `count < 3`. Because that is true, it prints `0`, increases `count` by 1, and checks again. The loop stops when `count` becomes `3`.

> A `while` loop always needs a way to become false. Most loops change a counter, a flag, or both.

## Working with a Loop Counter

A common use for `while` is counting upward or downward. This is helpful when you need exact control over each step.

### Counting upward

This example prints the numbers from 1 through 5. The condition uses `<=` because the final value should be included.

```python
number = 1

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

# Output:
# 1
# 2
# 3
# 4
# 5
```

Each pass through the loop changes `number`. That change is what eventually makes the condition false.

### Counting downward

You can also count down. This is useful for countdowns, retry timers, and cases where you need to start from a maximum and move toward zero.

```python
seconds = 3

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

print("Go!")

# Output:
# 3
# 2
# 1
# Go!
```

Because the last `print()` is outside the loop, it runs once after the countdown finishes.

## Stopping a Loop with break and continue

Sometimes the condition is not enough on its own. Python gives you `break` to stop early and `continue` to skip the rest of the current repetition.

### Using break to stop early

`break` ends the loop immediately. This is useful when you find what you were looking for before the condition becomes false.

```python
number = 1

while True:
    print(number)
    if number == 3:
        break
    number += 1

# Output:
# 1
# 2
# 3
```

Here the condition is always true, so the loop would never stop by itself. The `break` statement makes the loop finish when `number == 3`.

### Using continue to skip work

`continue` jumps to the next loop check. The rest of the body is skipped for that pass.

```python
number = 0

while number < 5:
    number += 1
    if number == 3:
        continue
    print(number)

# Output:
# 1
# 2
# 4
# 5
```

When `number` is `3`, Python skips the `print()` call and moves to the next condition check.

## Using while for Input Validation and Repetition

A `while` loop is often the simplest way to keep asking for input until the user gives a valid answer. This is a real-world use that a `for` loop does not handle as naturally.

```python
password = ""

while password != "python123":
    password = input("Enter the password: ")

print("Access granted")
```

This loop keeps running until the user types the expected string. The condition depends on user input, so the number of repetitions is not known ahead of time.

> This pattern is often called a sentinel loop. The sentinel is the special value that stops the loop.

## How while Loops Behave in Detail

Python checks the condition before each iteration, including the first one. That means the loop body may run zero times if the condition starts as false.

```python
temperature = 25

while temperature < 20:
    print("Too cold")

print("Done")

# Output:
# Done
```

The body never runs because `temperature < 20` is false from the start.

A `while` loop can also become infinite if the condition never changes. This usually happens when the code inside the loop forgets to update the value used in the condition.

```python
count = 1

while count <= 3:
    print(count)
    # count never changes here
```

That loop never stops because `count` stays equal to `1`. In a real program, that can lock up your script or keep printing forever.

**Warning:** Be careful with infinite loops in programs that read files, process data, or ask for input. A loop that never ends can make a program appear frozen.

Python also has an optional `else` clause for loops. The `else` block runs only if the loop ends normally, not if it exits through `break`.

```python
n = 1

while n <= 3:
    print(n)
    n += 1
else:
    print("Finished")

# Output:
# 1
# 2
# 3
# Finished
```

If you add a `break` inside the loop, the `else` block does not run. That detail matters when you use the `else` clause to mean “nothing stopped the loop early.”

## Common Mistakes with Python while Loops

### Forgetting to change the loop condition

This is the most common mistake. The loop condition stays true forever, so the loop never ends.

**Problem:** The value used in the condition never changes, so Python keeps repeating the loop forever.

```python
count = 1

while count <= 3:
    print(count)
```

**Fix:** Update the variable that controls the loop.

```python
count = 1

while count <= 3:
    print(count)
    count += 1
```

The corrected version works because the condition eventually becomes false.

### Using the wrong comparison operator

An off-by-one error often comes from using `<` when you meant `<=`, or the other way around. The loop may run one time too few or one time too many.

**Problem:** This loop stops before printing `5`, even though the goal is to include it.

```python
number = 1

while number < 5:
    print(number)
    number += 1
```

**Fix:** Use `<=` when the endpoint should be included.

```python
number = 1

while number <= 5:
    print(number)
    number += 1
```

The fixed version includes the final value because the condition stays true through `5`.

### Using continue without advancing the loop

`continue` is useful, but if you place it before the code that updates the condition, the loop may never progress.

**Problem:** When `number` equals `3`, the loop skips the increment and gets stuck on the same value.

```python
number = 0

while number < 5:
    if number == 3:
        continue
    number += 1
    print(number)
```

**Fix:** Make sure the loop variable changes on every path through the loop.

```python
number = 0

while number < 5:
    number += 1
    if number == 3:
        continue
    print(number)
```

The corrected version avoids getting stuck because `number` always advances before the skip.

### Using while on a sequence when for is simpler

Some beginners use `while` to walk through a list by index when a `for` loop would be clearer. This is not always wrong, but it is easier to make index mistakes.

**Problem:** This code can raise `IndexError: list index out of range` if the index goes past the last item.

```python
items = ["a", "b", "c"]
index = 0

while index <= len(items):
    print(items[index])
    index += 1
```

**Fix:** Use `<`, not `<=`, when the index must stay inside the valid range.

```python
items = ["a", "b", "c"]
index = 0

while index < len(items):
    print(items[index])
    index += 1
```

The fixed version stops at the last valid index, so it does not try to read past the list.

## Predict the Output

### Question 1

What does this print?

```python
count = 0
while count < 3:
    count += 1
    print(count)
```

**Answer:**

It prints 1, 2, and 3 on separate lines. The loop starts with `count` equal to 0, then increases it before printing. After the third pass, `count` becomes 3, and the next condition check fails.

```bash
# Output:
# 1
# 2
# 3
```

### Question 2

What happens here?

```python
items = [10, 20, 30]
index = 0
while index <= len(items):
    print(items[index])
    index += 1
```

**Answer:**

It prints 10, 20, and 30, then raises `IndexError: list index out of range`. The valid indexes are 0, 1, and 2, but the condition allows `index` to reach 3, which is one past the end of the list.

```bash
# Output:
# 10
# 20
# 30
# IndexError: list index out of range
```

## Find the Bug

Find the subtle bug in this loop. It looks like it should print 1 through 5, but it does not.

```python
number = 1

while number <= 5:
    if number == 3:
        continue
    print(number)
    number += 1
```

**Answer:**

The bug is that `number` is not increased when it equals 3, because `continue` skips the increment line. That leaves `number` stuck at 3 forever, so the loop never ends.

**Fixed code:**

```python
number = 1

while number <= 5:
    if number == 3:
        number += 1
        continue
    print(number)
    number += 1
```

The fixed version works because every path through the loop advances `number`.

## When to Use while Instead of for

Use `while` when the loop should keep going until a condition changes, not until a sequence is exhausted. Use `for` when you already know the items or the number of steps.

| Use this | When it fits | Example idea |
| --- | --- | --- |
| `while` | You do not know how many repetitions you need. | Keep asking for valid input |
| `for` | You want to repeat over items or a known range. | Print each item in a list |

A `while` loop is also a good choice when the stopping condition depends on something outside your code, such as a sensor reading, a file status, or user input.

Use `for` if you are only counting through a fixed sequence. It is easier to read and less likely to create an infinite loop or an off-by-one mistake.

### Interview question: Why use while instead of for?

A strong answer is: use `while` when the loop should continue until a condition becomes false and the total number of iterations is not known in advance. Use `for` when you already have a sequence or a clear range to iterate over.

### Interview question: What makes an infinite loop?

An infinite loop happens when the loop condition stays true forever. In Python, that usually means the code forgets to update the controlling variable, or it uses `while True` without a `break`.

### Interview question: What does the while else clause do?

The `else` block runs only if the loop finishes without `break`. It does not mean “run if the loop body ran.” It means “run if the loop ended normally.”

## Try It Yourself

Write a `while` loop that prints the even numbers from 2 to 8, inclusive.

- Start with a variable named `number` set to 2.
- Keep looping while `number` is at most 8.
- Print each value.
- Increase `number` by 2 each time.

**Expected output:**

```bash
# 2
# 4
# 6
# 8
```

**Hint:** The loop should change `number` by `2`, not by `1`.

**Solution:**

```python
number = 2

while number <= 8:
    print(number)
    number += 2

# Output:
# 2
# 4
# 6
# 8
```

## Summary

- A `while` loop repeats as long as its condition is true.
- Python checks the condition before each repetition, so the body may run zero times.
- Always update the variable that controls the condition, or the loop may never stop.
- Use `break` to exit early and `continue` to skip the rest of one pass.
- Use `while` when you do not know the number of repetitions in advance.
- The `else` clause runs only if the loop ends without `break`.

Next, learn `for` loops so you can compare fixed iteration with condition-based repetition.
