5. Randomness
An evolution sim needs randomness — creatures start in random spots, move in random directions, and their babies are slightly random too. That randomness is what makes evolution interesting. This page shows how to add luck to your programs.
Turning on the random tools
Python keeps its random tools in a toolbox called random. You bring it in with import at the very top of your file.
You only need to write import random once, at the top. After that you can use all its tools.
Pick a random item from a list — random.choice()
random.choice() reaches into a list and pulls out one item at random.
Output (yours may differ — that’s the point!):
Run it again and you’ll probably get a different direction. That’s randomness at work.
This is perfect for choosing a random creature to have a baby, or a random spot to place some food.
A random whole number — random.randint()
random.randint(low, high) gives you a random whole number between low and high. Both ends are included.
Output (varies):
random.randint(1, 6) is like rolling a dice — you get 1, 2, 3, 4, 5, or 6.
A random decimal — random.random()
random.random() gives a decimal number from 0.0 up to (but not quite reaching) 1.0. This is brilliant for “does this happen or not?” chances.
Output (varies):
Using it for a percentage chance
Say you want a mutation to happen 10% of the time. 10% is 0.1. So: if the random number is less than 0.1, the mutation happens.
Because random.random() is a fresh random number every time, roughly 1 time in 10 you’ll see the mutation message. Change 0.1 to 0.5 and it’ll happen about half the time.
Why randomness makes evolution work
Here’s the big idea behind your sim:
- Creatures are all slightly different (some faster, some slower) — thanks to random mutations.
- The differences that help a creature survive and have babies get passed on.
- Over many generations, the whole group slowly changes to suit the world.
Randomness is the spark. Without it, every creature would be identical and nothing would ever improve. You’ll use random.choice, random.randint and random.random all over your sim.
A tiny example: a slightly-mutated baby
Here’s how you might make a baby creature that’s almost like its parent, but with a small random change to its speed:
Output (varies):
Do this for lots of babies over lots of generations, keep the faster ones alive, and — evolution!
✅ Quick recap
- Write
import randomonce at the top of your file. random.choice(a_list)picks a random item from a list.random.randint(1, 6)gives a random whole number (both ends included).random.random()gives a decimal from 0.0 to 1.0 — great for chances.if random.random() < 0.1:makes something happen about 10% of the time.