INTRODUCTION
Do it again
A for loop repeats lines for each item.
press Enter ↵
🐍 main.py
Ctrl + Enter runs it too. Esc, then Tab, leaves the code.
Output

Press ▶ Run to see what your program does.

Lesson 36: for loops

Level 5, Python Thinks and Repeats. Repeat lines for each number in a range. The new word: for loop. It follows lesson 35, Comparisons and indents. Next comes lesson 37, while loops.

What the lesson explains

Do it again. A for loop repeats lines for each item.

for i in range(3). i takes each number in turn: 0, then 1, then 2. On the card: for i in range(3):

What you do first

Count to five. Print 1 to 5, one on each line. One way to write it: for n in range(1, 6): / print(n). It prints: 1 / 2 / 3 / 4 / 5.

The code on the screen

for i in range(3). The editor shows 2 lines: for i in range(3): / print("Hip hip hooray!", i). Run it, and it prints "Hip hip hooray! 0", "Hip hip hooray! 1", "Hip hip hooray! 2".

How many times?. The editor shows 2 lines: for i in range(4): / print("hi"). Run it, and it prints "hi", "hi", "hi", "hi".

What you practise

Try it, "Count to five": Print 1 to 5, one on each line. One way to write it: for n in range(1, 6): / print(n). It prints: 1 / 2 / 3 / 4 / 5.

Try it, "A times table": Print the 3 times table up to 15. The editor opens with: for n in range(1, 6):. One way to write it: for n in range(1, 6): / print(3 * n). It prints: 3 / 6 / 9 / 12 / 15.

In your head, "How many times?": for i in range(4): print("hi") — how many hi? The answer: "4".

What PlayBuddy and PlayType say

PlayType: "Doing the same thing ten times? Let a loop do it for you!"

PlayBuddy: "Range counts for you. It starts at zero, and stops just before the end."

Help in every lesson

Everything happens on a pretend computer in your browser, so nothing touches your real files. PlayBuddy and PlayType stand beside the board, cheer you on and say when it is your turn.

A green ring shows where to click the first time. After that you do it on your own, and if you slip twice the ring comes back.

Stars

The lesson has 3 things to do. Up to one slip in ten gives three stars, up to one in four gives two, and finishing always gives at least one. Stars and progress are saved in this browser only; there is no account.

About DayOneCode

DayOneCode is an independent learning site, not affiliated with or endorsed by Anthropic. Claude and Claude Code are trademarks of Anthropic.