Exerpad
Lesson · Chapter: While Loops+10 XP for reading

Repeating with While

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

Basic While Loop

python
i = 1
while i <= 5:
print(i)
i = i + 1
Output
Press Run to see the output.

Output:

1
2
3
4
5

How It Works

  1. Check the condition
  2. If true, run the indented code
  3. Go back to step 1
  4. If false, skip ahead

Don't Forget to Update!

If you forget to change the counter, the loop runs forever:

python
# BAD — infinite loop!
i = 1
while i <= 5:
print(i)
# Oops, forgot i = i + 1
Output
Press Run to see the output.

Always make sure the condition will eventually become false.

Counting Down

python
count = 5
while count >= 1:
print(count)
count = count - 1
print("Go!")
Output
Press Run to see the output.

Breaking Out

Use break to exit a loop early:

python
while True:
answer = input()
if answer == "quit":
break
print("You said:", answer)
Output
Press Run to see the output.

Adding Things Up

The accumulator pattern — start with 0 and keep adding:

python
total = 0
i = 1
while i <= 5:
total = total + i
i = i + 1
print("Sum:", total)
Output
Press Run to see the output.

Output:

Sum: 15