4. Loops

Computers are brilliant at repeating things. A loop runs the same block of code again and again, so you don’t have to copy-paste it. Your evolution sim will use loops constantly — one step of the world happens, then the next, then the next…

There are two kinds: for loops and while loops.


The for loop — repeat once per item

You met this on the lists page. A for loop goes through a list, one item at a time.

food_items = ["berry", "leaf", "seed"]

for food in food_items:
    print(f"A creature nibbles a {food}.")

Output:

A creature nibbles a berry.
A creature nibbles a leaf.
A creature nibbles a seed.

Counting with range()

Sometimes you don’t have a list — you just want to do something a set number of times. range() gives you a run of numbers to loop over.

for step_number in range(5):
    print(f"World step {step_number}")

Output:

World step 0
World step 1
World step 2
World step 3
World step 4

Notice range(5) gives 0, 1, 2, 3, 4 — that’s five numbers, but it starts at 0 and stops before 5.

You can also choose where to start and stop:

for generation in range(1, 4):    # start at 1, stop before 4
    print(f"Generation {generation}")

Output:

Generation 1
Generation 2
Generation 3

The while loop — repeat as long as something is true

A while loop keeps going for as long as its test is True. It checks the test, runs the block, checks again, runs again… until the test becomes False.

creature_energy = 100

while creature_energy > 0:
    print(f"The creature is alive with {creature_energy} energy.")
    creature_energy -= 25      # lose 25 energy each time round

print("The creature has run out of energy.")

Output:

The creature is alive with 100 energy.
The creature is alive with 75 energy.
The creature is alive with 50 energy.
The creature is alive with 25 energy.
The creature has run out of energy.

The loop stopped as soon as creature_energy > 0 became False.

⚠️ The infinite loop trap

If the test never becomes false, the loop runs forever and your program freezes. This is a very common bug!

# 🚫 DON'T RUN THIS — it never stops!
creature_energy = 100
while creature_energy > 0:
    print("Still going...")
    # oops — we forgot to take energy away, so it's always > 0

The fix: always make sure something inside the loop changes, moving you closer to stopping. In the good example above, creature_energy -= 25 was that something.

(If you ever do get stuck in an infinite loop, you can usually stop it by pressing Ctrl + C in the window where it’s running.)


break — jump out of a loop early

break stops a loop immediately, even if it wasn’t finished.

food_items = ["berry", "leaf", "poison", "seed"]

for food in food_items:
    if food == "poison":
        print("Poison! Stop eating right now!")
        break
    print(f"Ate a {food}, yum.")

Output:

Ate a berry, yum.
Ate a leaf, yum.
Poison! Stop eating right now!

The loop never reached “seed” because break jumped out.


continue — skip to the next item

continue skips the rest of this turn and jumps to the next one.

food_items = ["berry", "rock", "leaf", "rock", "seed"]

for food in food_items:
    if food == "rock":
        continue      # rocks aren't food — skip and move on
    print(f"Ate a {food}.")

Output:

Ate a berry.
Ate a leaf.
Ate a seed.

The rocks were skipped, but the loop carried on.


Which loop should I use?

  • Use a for loop when you know what you’re looping over — a list, or a set number of times.
  • Use a while loop when you want to keep going until something changes — like “keep the game running while the player hasn’t quit”.

In fact, your pygame game will have one big while loop at its heart, called the game loop. You’ll see it in 10. pygame Basics.


✅ Quick recap

  • for item in a_list: repeats once per item.
  • for number in range(5): repeats a set number of times (0 to 4).
  • while test: repeats as long as the test is True.
  • Always change something inside a while loop, or it runs forever!
  • break jumps out of a loop; continue skips to the next turn.