Kids Coding
Random Surprises
import random. Pick a number, a word, or a choice so each run is different.
KidsIntermediateRandom Surprises
Make each run different
import random loads a toolbox. Then you can pick a number or an item.
A dice
import random
print(random.randint(1, 6))
print(random.randint(1, 6))import random goes at the very top of the file, once. Forget it and Python says name 'random' is not defined.
Pick from a list
choice
import random
pets = ["cat", "dog", "fox"]
print(random.choice(pets))A secret number
This is the missing piece from the Basic guess game.
Random secret
import random
secret = random.randint(1, 5)
guess = 3
print("Secret was", secret)
if guess == secret:
print("Lucky")
else:
print("Not this time")Real life
Picking who goes first in a board game.
A die is random. randint is a die the computer rolls for you.
Who starts
import random
players = ["Sam", "Riley", "Jun"]
print("Starts:", random.choice(players))
print("Dice:", random.randint(1, 6))Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Print a random colour from ["red", "green", "blue"].
Show solution
import random
print(random.choice(["red", "green", "blue"]))