Loops in Python: Repeating Yourself Without Losing Your Mind
Repeat tasks with for loops, range(), and while loops, and control them with break and continue without trapping yourself in an infinite loop.
You'll learn when to use a for loop vs a while loop, how range() counts (and why it stops one number early), and how break and continue steer loops. Assumes basic Python variables and if/else.
1. Computers never get bored
If you need to greet 500 users or rename 200 files, writing 500 print() lines is a great way to question your life choices. A loop runs one indented block of code repeatedly.
Python has two loops:
for— "Do this once for every item in a collection."while— "Keep doing this as long as a condition stays True."
excuses = ["cache", "DNS", "cosmic rays"]
for excuse in excuses:
print(f"Blaming {excuse}...")Blaming cache...
Blaming DNS...
Blaming cosmic rays...2. Counting with range()
When you just want to repeat something N times, use range():
for i in range(1, 4):
print(f"Round {i}")Round 1
Round 2
Round 3Notice range(1, 4) printed 1, 2, 3—it stops before 4. range(3) starts at 0 and gives 0, 1, 2. That off-by-one rule is consistent everywhere in Python (lists, slices, range), so once you learn it once, it applies everywhere.
Run for n in range(10, 0, -2): print(n) to see how a negative third argument counts backward by 2.
3. Repeating until done with while
Use while when you don't know upfront how many loops it will take:
tries = 3
while tries > 0:
print(f"Connecting... ({tries} left)")
tries -= 1
print("Giving up.")Connecting... (3 left)
Connecting... (2 left)
Connecting... (1 left)
Giving up.Always change the condition inside the loop (tries -= 1). If the condition stays True forever, your script hangs until you hit Ctrl+C in the terminal.
4. Skipping and escaping: continue and break
continueskips the rest of the current lap and jumps to the next item.breakexits the loop completely right now.
for n in range(1, 7):
if n == 3:
continue
if n == 5:
break
print(n)1
2
4Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
| Script freezes forever | while condition never becomes False | Press Ctrl+C and update the loop variable inside the loop |
TypeError: 'int' object is not iterable | Wrote for i in 5: | Use for i in range(5): |
Missing last number in range(1, 10) | range(start, stop) excludes stop | Use range(1, 11) |
Practice
- What does
for ch in "hi": print(ch)print? - How many times does
for i in range(5):run?
Answers:
hon the first line,ion the second line.- 5 times (
0, 1, 2, 3, 4).
What you learned
forsteps through lists, strings, orrange(start, stop).whilerepeats as long as a condition isTrue—make sure it can eventually becomeFalse.continueskips one iteration;breakexits the loop.