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:
text
1 2 3 4 5
How It Works
- Check the condition
- If true, run the indented code
- Go back to step 1
- 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
Always make sure the condition will eventually become false.
Counting Down
python
count = 5
while count >= 1:
print(count)
count = count - 1
print("Go!")
Breaking Out
Use break to exit a loop early:
python
while True:
answer = input()
if answer == "quit":
break
print("You said:", answer)
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:
text
Sum: 15