random: make things surprising
Computers usually do the exact same thing every time. The random module breaks that — it lets your code roll dice, pick surprises, and scatter things all over.
The big idea
The random module gives your code surprises — like a random number, or a random pick from a list.
See it in code
The plainest surprise is a random number. random.randint(1, 6) rolls a number between 1 and 6, like a dice. We call random.seed(5) first so you get the same rolls we did:
import random
random.seed(5)
print("A random number 1-6:", random.randint(1, 6))
print("Another:", random.randint(1, 6))A random number 1-6: 5 Another: 3
Two rolls, two surprises. The seed makes them repeatable — without it, you'd get different numbers every run.
random can also pick from a list for you. random.choice(colors) grabs a surprise item, so a loop can hand each star its own color:
import random
random.seed(5)
colors = ["red", "blue", "green", "yellow"]
for i in range(4):
print("star", i, "->", random.choice(colors))star 0 -> green star 1 -> green star 2 -> red star 3 -> yellow
Sometimes the same color comes up twice in a row — that's real randomness, not a bug! This is exactly how we'll pick each star's color on the canvas.
Now paint a starfield where no two stars are alike. random.randint(40, 460) picks a surprise spot for each star, and random.choice(PALETTE) grabs a surprise color — with a seed up front so the same sky shows up every run:
import random
from art import Canvas, PALETTE, star
screen = Canvas.create()
Canvas.fill(screen)
random.seed(5)
for i in range(20):
x = random.randint(40, 460)
y = random.randint(40, 460)
star(screen, x, y, size=30, color=random.choice(PALETTE))
randint gives each star a random spot and choice a random color — the same two tools from the warm-ups — so the starfield looks natural instead of neat. Remove the seed line and you'd get a brand-new sky each run.
Randomness makes things feel alive. Games roll dice and shuffle cards. Art scatters shapes. Quizzes pick a surprise question. Any time you want a surprise instead of the same thing, reach for random.
Try it yourself
Change range(20) to range(60) for a thicker starfield. Then change the seed number from 5 to 9 and watch a totally different sky appear.
The common mistake
Forgetting to import random. The random tools live in a module, so random.randint(...) only works after you write import random at the top. Miss it, and Python won't know what random means.
What it unlocks
Randomness builds on imports and powers generative art and randomness in art.