> Source URL: /resources/while-loops.guide
# While Loops

A `while` loop repeats a block of code as long as a condition is true.

## Basic Structure

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

Output:

```
1
2
3
4
5
```

_Note: The indented code runs repeatedly until the condition becomes `False`._

## Infinite Loops with `while True`

Use `while True:` to create a loop that runs forever (until you `break` out of it):

```python
while True:
    answer = input("Type 'quit' to exit: ")
    if answer == "quit":
        break
    print("You typed: " + answer)
```

_The `break` statement immediately exits the loop._

## The `break` Statement

Use `break` to exit a loop early:

```python
count = 1
while count <= 10:
    print(count)
    if count == 5:
        print("Stopping early!")
        break
    count = count + 1
```

Output:

```
1
2
3
4
5
Stopping early!
```

## The `continue` Statement

Use `continue` to skip to the next iteration:

```python
count = 0
while count < 5:
    count = count + 1
    if count == 3:
        continue  # skip printing 3
    print(count)
```

Output:

```
1
2
4
5
```

## Input Validation Example

A common use of `while` loops is to keep asking until the user gives valid input:

```python
color = ""
while color != "red" and color != "blue":
    color = input("Pick red or blue: ")
print("You picked " + color)
```

## Game Loop Example

Many games use `while True:` as their main loop:

```python
health = 100

while True:
    print("Health: " + str(health))
    action = input("Attack or run? ")

    if action == "run":
        print("You escaped!")
        break
    elif action == "attack":
        health = health - 10
        if health <= 0:
            print("Game over!")
            break
```

## Common Mistakes

**Forgetting to update the loop variable**

```python
# Wrong - infinite loop!
count = 1
while count <= 5:
    print(count)
    # Oops, forgot to increase count

# Right
count = 1
while count <= 5:
    print(count)
    count = count + 1
```

**Forgetting the colon**

```python
# Wrong
while count <= 5
    print(count)

# Right
while count <= 5:
    print(count)
```

**Incorrect indentation**

```python
# Wrong - print is not inside the loop
while count <= 5:
print(count)

# Right
while count <= 5:
    print(count)
```


---

## Backlinks

The following sources link to this document:

- [While Loops Guide](/resources/resources.index.llm.md)
- [while loops](/unit-1/projects/03-pet-py/pet-py.project.llm.md)
- [While Loops](/unit-2/projects/04-oracle/oracle-handbook.guide.llm.md)
