Loops: Teaching a Program to Repeat

← Back to Blog & Articles

Computers are very good at repeating things. A loop lets you write an instruction once and have it run as many times as you need.

The for loop

A for loop repeats a block a set number of times:

for i in range(5):
    print("Hello!")

This prints "Hello!" five times. The variable i counts 0, 1, 2, 3, 4, and you can use it inside the loop.

The while loop

A while loop repeats as long as a condition stays true. It is useful when you do not know in advance how many repeats you will need, such as asking for a password until it is correct.

Avoid the endless loop

If the condition never becomes false, the loop never ends. Make sure something inside the loop changes the condition, and learn how to stop the program in your editor.

Looping over a list

You can go through each item in a list, such as a list of animal names, and do something with each one.

Common mistakes

  • Forgetting the colon at the end of the loop line.
  • Forgetting to indent the repeated code.
  • Being off by one, because range(5) stops before 5.

Challenge ideas

  • Print a times table.
  • Count down from 10 and then print "Liftoff!".
  • Add up the numbers from 1 to 100.

Takeaway

Loops save effort and make programs short, which is a big part of what makes computers useful.

Continue with the book

Explore the full treatment, worked examples, and exercises in Code Quest with Python.


Adapted from Code Quest with Python, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top