Skip to content

The for loop

If you need to print the word “Hello” 100 times, are you going to write 100 print lines? No way! That’s what a loop is for.

Inputs (for input())

One value per line — read in order by input().

Output
 

Read it as: “repeat 5 times: print Hello”. The indentation rule applies here too — the lines inside the loop are 4 spaces in.

i is just an ordinary variable, and its value changes on every repeat. Look:

Inputs (for input())

One value per line — read in order by input().

Output
 

Not what you expected, right? It started at 0 and ended at 4! Programmers love counting from 0. range(5) = “0, 1, 2, 3, 4” — that’s 5 numbers in total, but starting at 0.

  • range(5) → 0, 1, 2, 3, 4
  • range(1, 6) → 1, 2, 3, 4, 5 — from a start up to an end (the last number is not included!)
Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

The repeat machine

+10 XP

Print the sentence Python is great! 10 times — but write print only once in your code.

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

1 to 10

+15 XP

Print the numbers from 1 to 10 in order. Careful: in range, the last number is not included!

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Times table

+15 XP

Solve it with code before the teacher even finishes writing it on the board: the 5 times table, from 1 to 10, in the format 5 x 3 = 15.

Inputs (for input())

One value per line — read in order by input().

Output
 

Next lesson: loop + variable = superpower. We’ll add up every number from 1 to 100 in a split second — like a little Gauss. Continue →