Loops: for and while

What a loop is; iterate with for, repeat with while.

1. What is this?

A loop repeats a block. A for loop walks through a sequence: for i in range(5) runs with i = 0..4. range(1, 6) gives 1..5. Indentation (the spaces at the line start) marks which lines belong to the loop. A while loop repeats while a test stays true.

2. Why do we use it?

Processing rows, retrying, counting — loops turn one block into many executions.

3. Syntax breakdown

  • for i in range(1, 6):

    Repeat with i = 1,2,3,4,5. The colon starts the block.

  •     print(f"Step {i}")

    Indented line = inside the loop. Runs once per i.

  • print("Done")

    Not indented = after the loop. Runs once.

5. Common mistakes

  • Forgetting the colon after for ...: — Python requires it.
  • Inconsistent indentation — use 4 spaces per level, always.
  • Thinking range(5) includes 5 — it stops at 4.

Practice task

Print the 3-times table: lines like "3 x 1 = 3" up to 3 x 5.

Hint

Use for i in range(1, 6): and print(f"3 x {i} = {3 * i}").

Try it below — tests run automatically when you press Run.

python

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. Which values does range(1, 6) give?

  2. 2. How does Python know which lines are in the loop?

  3. 3. What ends a for header line?

4. Example — edit and run

python

Output

Press Run to see output.

Expected output: Step 1