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.
Output:
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.
Output:
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:
Output:
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.
Output:
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!
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.
Output:
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.
Output:
The rocks were skipped, but the loop carried on.
Which loop should I use?
- Use a
forloop when you know what you’re looping over — a list, or a set number of times. - Use a
whileloop 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 isTrue.- Always change something inside a
whileloop, or it runs forever! breakjumps out of a loop;continueskips to the next turn.