A Splash of Randomness
Everything you’ve drawn so far comes out exactly the same every time. Today that changes. You’ll let the computer make random choices, so each Run is a little surprise. This is the secret behind “generative art,” where the artist writes the rules and the computer fills in the details.
Asking for a random number
Python has a helper for randomness. Switch it on with import random at the top, then:
random.randint(1, 6)— a random whole number from 1 to 6 (like rolling a die).random.choice(["red", "blue", "green"])— randomly pick one item from a list.
Here’s a circle whose color is chosen at random. Press Run a few times — it changes!
That colors line is a list — several values inside square brackets. random.choice reaches in and grabs one.
Try it 🎯
- Run it several times and watch the color change.
- Add
"hotpink"and"cyan"to the list. Run again. - Change
t.circle(70)tot.circle(random.randint(30, 120))— now the size is random too!
Predict it 🔮
random.randint(1, 3) gives 1, 2, or 3. Roughly how many of the lines below do you think will print “small”? Run it a few times to see how the surprise works:
(About one in three runs prints “small” — randint(1, 3) lands on 1 roughly a third of the time.)
Scatter with randomness
Randomness gets really fun when you scatter things. t.goto(x, y) moves the turtle, and we pick random spots, sizes, and colors:
Twenty dots — each a random spot, size, and color. Confetti! And every Run is different. You wrote the rules; the computer made the choices.
Try it 🎯
- Change
range(20)torange(60)for way more dots. - Change
randint(5, 25)torandint(10, 60)for bigger blobs. - Make your own color list.
Fix the bug 🐞
This is meant to scatter dots all over, but they all pile up in the same spot. The goto always jumps to the exact center. Make the position random:
(Change t.goto(0, 0) to t.goto(random.randint(-200, 200), random.randint(-200, 200)).)
Mix it up 🎨
Take the confetti and make the dots all shades of one color (say a list of just blues: ["navy", "blue", "deepskyblue", "turquoise"]) for an “ocean” feel. Then try all warm colors for a “fire” feel.
Your mission 🚀
Make a random night sky: scatter 30 small dots (stars) in random spots, all in light colors like "white", "lightyellow", and "gold". Start from the confetti code and adjust the count, sizes, and color list.
What you learned today
import randomswitches on randomness.random.randint(a, b)gives a random number;random.choice(list)picks a random item.- A list holds many values:
["red", "blue", "green"]. - Random choices make art that’s different every Run.
Next time, the turtle learns to make decisions with if — so it can choose what to draw, not just what color. Then we put it all together for your capstone. 🐢
Comments