🐍 Python Tutorial

← PrevNext →

Python Loops

Master for and while loops in Python.

Python Loops

Loops are used to repeat actions multiple times.

The for Loop

for i in range(3):
    print("Hello", i)

The while Loop

count = 0
while count < 3:
    print("Count:", count)
    count += 1

Breaking Out of a Loop

for i in range(10):
    if i == 5:
        break
    print(i)

Common Errors & Troubleshooting

  • IndentationError: expected an indented block — the line(s) inside a for/while loop must be indented (4 spaces is the Python convention). Forgetting to indent the body under the loop line causes this.
  • Infinite loop that never stops — a common while loop bug: forgetting to update the condition variable inside the loop (e.g. leaving out count += 1), so count < 3 is always true. Press Ctrl+C in the terminal to force-stop a runaway script.
  • range(3) doesn't include 3 — range(3) produces 0, 1, 2 — it's exclusive of the stop value. Use range(1, 4) if you actually want 1, 2, 3.