Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Loops: for & while

16 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 6 of 7 · View course roadmap
Step 1

Learn the idea

Loops let you repeat work without repeating code — the superpower that makes computers useful.

for loops walk through a sequence. range(5) produces 0,1,2,3,4 (start at 0, stop before 5). range(1, 6) gives 1–5.

while loops repeat as long as a condition stays True — perfect when you don't know how many repetitions you need.

  • break — exit the loop immediately
  • continue — skip to the next iteration
  • Beware infinite while loops — make sure something changes the condition!

Where you'll use this

Loops process every row of a spreadsheet, every user in a database, every line of a log file. 'For each order, send an email' — that sentence is a for loop, and automation careers are built on it.

Common mistakes

  • Off-by-one with range: range(5) is 0–4. Want 1–5? range(1, 6).
  • Infinite while loops — forgetting to change the loop variable inside the body.
  • Modifying a list while looping over it — skips elements unpredictably. Loop over a copy: for x in items[:].

Pro tip

Need the index AND the value? Never do range(len(items)) — use enumerate: for i, item in enumerate(items). Looping two lists together? zip(names, scores).

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +30 XP

Blank · autosaved

Use a for loop with range to print the squares of the numbers 1 through 5, one per line (1, 4, 9, 16, 25).

Target output
1
4
9
16
25
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. What numbers does range(3) produce?
2. What does break do inside a loop?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path