Introduction to Programming

Lesson 4 of 7

Loops

Automate repetitive tasks and write efficient code using Python for and while loops.

🟢 Beginner 80 XP

Learn it

If you had to write a message 100 times on a chalkboard, your hand would get exhausted! Programmers are clever: they use loops to repeat code automatically.

Python has two main kinds of loops: for loops (great when you know how many times you want to repeat) and while loops (great when you want to repeat until something changes).

Key terms

Loop
A control structure that repeats a block of code multiple times.
Iteration
A single pass or repetition through a block of looped instructions.
For Loop
A loop designed to repeat instructions a predetermined number of times or over a sequence.
While Loop
A loop that continues executing as long as a specified condition remains true.

Inside a Loop Cycle

See how a countdown loop evaluates and repeats until its exit condition is met.

  1. 1Initialisation: A counter variable is set to a starting number, for instance timer = 3.
  2. 2Condition Check: Python evaluates whether timer > 0 is True.
  3. 3Body Execution: The indented block runs, printing the current timer count to the player.
  4. 4Decrement & Repeat: The timer decreases by 1 and execution loops back to the condition check.

Printing Repetitive Actions with Loops

pythonprint("Starting laser charge:")
for i in range(1, 4):
    print("Charging power level:", i)

print("Lasers fully charged!")

The for loop uses range(1, 4) to run the indented print line three times, with i taking values 1, 2, and 3.

Try it

Predict the final number outputted by this Python code:

pythontotal = 0
for i in range(3):
    total = total + 2
print(total)

Challenge

Write a for loop in Python that prints the numbers 5, 4, 3, 2, 1 followed by Blast off!

Pick whichever way suits you — every mode earns the same bonus XP.

Write at least 40 more characters to submit.

Mark your own work

Guided walkthrough — 0/5 clues revealed

  1. Clue 1 locked — reveal it only if you get stuck.
  2. Clue 2 locked — reveal it only if you get stuck.
  3. Clue 3 locked — reveal it only if you get stuck.
  4. Clue 4 locked — reveal it only if you get stuck.
  5. Clue 5 locked — reveal it only if you get stuck.

Each clue costs 4 XP (never below 20 XP). You'd earn 40 XP right now.

Extension: Rewrite the countdown using a while loop that decreases a rocket_timer variable.

Quiz time

Question 1 of 4Score 0

What is the primary benefit of using loops in code?