> For the complete documentation index, see [llms.txt](https://kallyasmedia.gitbook.io/cit-python-cohort-three/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kallyasmedia.gitbook.io/cit-python-cohort-three/week2/while_loops.md).

# Control Flow / While Loops

Use a `while` loop to repeat a block of code as long as a condition is true. This is useful when you do not know in advance how many iterations you need.

## Syntax

```python
while condition:
    # code block
```

## Example

```python
total = 0
counter = 1
n = 5

while counter <= n:
    total += counter
    counter += 1

print(total)  # 15
```

## `while` ... `else`

The `else` block runs only if the loop finishes without a `break`.

```python
counter = 0

while counter < 3:
    print("Loop")
    counter += 1
else:
    print("Done")
```

## Common Pitfalls

* Forgetting to update the loop variable (infinite loop).
* Using a `while` loop where a `for` loop is clearer.

[Next](/cit-python-cohort-three/week2/break_and_continue.md) | [Previous](/cit-python-cohort-three/week2/for_loop.md)
