🐍 Python Topic Library

Python Loops — for, while, range, break & continue

Loops are how programs do the boring work a million times without complaining. Python's for loop is famously clean — once you stop fighting range() and off-by-ones.

⚡ Quick Answer

for item in sequence: visits each element. range(5) gives 0-4. while condition: repeats until false. break exits the loop, continue skips to the next round. Need the index too? for i, item in enumerate(items):.

§for — loop over anything

for_basics.py
for letter in "abc":
    print(letter)              # a b c

scores = [90, 85, 77]
for s in scores:
    print(s * 2)

for i in range(5):             # 0 1 2 3 4 — five numbers, ends BEFORE 5
    print(i)

for i in range(2, 11, 2):      # start, stop, step → 2 4 6 8 10
    print(i)

§while — repeat until told to stop

while_basics.py
count = 3
while count > 0:
    print(count)
    count -= 1        # forget this line = infinite loop!
print("liftoff 🚀")

# the input-validation pattern:
answer = ""
while answer not in ("yes", "no"):
    answer = input("yes or no? ").lower()

§break & continue

control.py
for n in range(1, 100):
    if n * n > 50:
        print(f"first square over 50: {n*n}")
        break                 # exit loop entirely

for n in range(10):
    if n % 2 == 0:
        continue              # skip evens, go to next n
    print(n)                  # 1 3 5 7 9

§enumerate & zip — the pro loops

pro_loops.py
names = ["ada", "alan", "grace"]

for i, name in enumerate(names, start=1):
    print(f"{i}. {name}")       # numbered list, no manual counter

scores = [95, 88, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score}")   # two lists in parallel

§Nested loops

nested.py
for row in range(3):
    for col in range(3):
        print(f"({row},{col})", end=" ")
    print()                     # newline after each row
# total iterations = 3 × 3 = 9 — nesting multiplies work!

§Common Mistakes to Avoid

🚨 Watch out for these
  • Infinite while loops — if nothing inside the loop changes the condition, it never ends — Ctrl+C to stop, then fix the update line
  • Expecting range(5) to include 5 — range stops BEFORE the end value: range(5) is 0-4; use range(1, 6) for 1-5
  • Modifying a list while looping it — removing items inside for x in items: skips elements — loop over items[:] (a copy) instead

§Frequently Asked Questions

When should I use for vs while?

Use for when you know what you're looping over (a list, a range, a file); use while when you loop until some condition changes, like waiting for valid input.

What does range(1, 10, 2) mean?

Start at 1, stop before 10, step by 2 — producing 1, 3, 5, 7, 9.

How do I get the index inside a for loop?

Wrap the sequence with enumerate(): for i, item in enumerate(items). Avoid the manual counter pattern.

What is an infinite loop and how do I stop one?

A while loop whose condition never becomes False. Press Ctrl+C to interrupt it, then make sure something inside the loop updates the condition.

🎓 Want to master Python properly?This reference covers one topic — the full free course takes you from zero to projects, with quizzes and a certificate.
Start the Free Python Course →

§Related Python Topics

← If / ElseFunctions →