Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Change the flow
EXPERIMENT 08 / 101

Put repetition on autopilot.

Visit items, count with range, and stop doing repetitive work by hand.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

A for loop visits the items of an iterable one at a time. A list, string, or range can supply those items. The loop variable is assigned each item in turn. Use enumerate() when you need both a position and a value.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

for_loops.py
for step, task in enumerate(["design", "build", "test"], start=1):
    print(f"{step}. {task}")

print(list(range(2, 8, 2)))
↳ EXPECTED OUTPUT
1. design
2. build
3. test
[2, 4, 6]

03 Under the hood

  1. 1

    enumerate() pairs each task with a counter. start=1 makes the display human-friendly without changing list indexing.

  2. 2

    range(2, 8, 2) produces values beginning at 2, stepping by 2, and stopping before 8.

  3. 3

    Indent all instructions that should repeat. Put the summary after the loop, at the outer indentation level. A for loop over an empty iterable runs its body zero times.

04 Your turn, builder

A SMALL MISSION

Print the squares of 1 through 4, one per line.

Reveal one possible solution +
one_possible_solution.py
for number in range(1, 5):
    print(number ** 2)

05 Check your signal

QUICK SIGNAL CHECK

What values does range(3) supply?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.