Randomness: let the computer surprise you
Most code does the same thing every time. Randomness breaks that rule on purpose. It's how a program picks a surprise, rolls a dice, or paints a sky that's never the same twice.
The big idea
The random tools let the computer choose for you: one item from a list, or a whole number between two ends.
See it in code
random.choice() picks one item from a list. Every item has the same chance:
import random
flavors = ["snickerdoodle", "oatmeal", "sugar cookie", "cinnamon swirl"]
print("Surprise cookie:", random.choice(flavors))Surprise cookie: sugar cookie
Press the 'Run Code' button a few times. The same code gives different answers, and that's the whole point.
random.randint(1, 3) picks a whole number from 1 to 3. Both ends count, so it can pick 1, 2, or 3:
import random
for customer in range(8):
discount = random.randint(1, 3)
print("Discount: $", discount)Discount: $ 2 Discount: $ 1 Discount: $ 2 Discount: $ 3 Discount: $ 1 Discount: $ 1 Discount: $ 3 Discount: $ 1
The pick sits inside the loop, so it happens fresh on each trip. Put it above the loop and all eight customers would get the same number.
The paint studio has its own random tools: random_number(low, high) and pick(list). Here each spark flies to a random spot in a random color:
spark_count = 24
spread = 110
burst_x = 200
burst_y = 150
burst_colors = ["gold", "orange red", "white"]
paper("midnight blue")
for count in range(spark_count):
end_x = burst_x + random_number(-spread, spread)
end_y = burst_y + random_number(-spread, spread)
line(x1=burst_x, y1=burst_y, x2=end_x, y2=end_y, color=pick(burst_colors), width=2)
dot(x=end_x, y=end_y, color="white")
rect(x=200, y=375, width=400, height=50, color="black")
end_x is random, and it's stored in a jar. That lets the line and the dot share the same spot, so each spark has a bright tip.
Games lean on chance all the time. A cupcake drops from a random spot. A power-up appears one time in five. Without randomness, every game would play out the same.
Try it yourself
Change spark_count to 60 and spread to 160. Run it three times and compare. Then put your own three colors in burst_colors.
The common mistake
Expecting randint to work like range. range(1, 3) stops before 3. But random.randint(1, 3) includes 3. Both ends count when the computer is picking.
What it unlocks
Random tools arrive through an import. Put a random pick inside a for loop and you're making generative art, art that's different every time.