random: let the program surprise you
Section 11: Randomness and errorsLesson 11.1 · ⏱ 8 min
The random library picks things by chance, and it is the base of every game.
random.randint(1, 6)is a number from 1 to 6, like a dice.random.choice(list)is a random item from the list.random.shuffle(list)mixes up the order of the list.random.seed(7)makes “chance” repeat with the same result, which is useful when testing code. Delete it so the result changes every time.
import random
random.seed(7)
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))
colors = ["red", "green", "blue"]
random.shuffle(colors)
print(colors)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗3 rock ['blue', 'red', 'green']

📌 Note
With
random.seed(7) you'll get the same result you see here. Delete that line and run several times.📌 Another example: rock, paper, scissors
The computer chooses with random.choice. (seed so we get the same result every time.)
When the program asks, we type: rock.
import random
random.seed(2)
me = input("rock, paper or scissors? ")
pc = random.choice(["rock", "paper", "scissors"])
print("computer:", pc)
if me == pc:
print("draw")
elif (me, pc) in [("rock", "scissors"), ("paper", "rock"), ("scissors", "paper")]:
print("you win")
else:
print("you lose")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗rock, paper or scissors? rock computer: rock draw
✍️ Practise
Delete the seed line and run the program three times. Did the result change?
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Print 5 random numbers between 1 and 100.
👀 Show the solution🙈 Hide the solution
import random
for i in range(5):
print(random.randint(1, 100))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗12 11 47 22 95
Result: five different numbers every time.
Medium
Choose a random name from the list to start the game.
👀 Show the solution🙈 Hide the solution
import random
names = ["Ali", "Mona", "Omar", "Sara"]
print(random.choice(names), "starts!")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Omar starts!
Result: a random name, then starts!
Hard
A random password of 6 digits.
👀 Show the solution🙈 Hide the solution
import random
pw = ""
for i in range(6):
pw = pw + str(random.randint(0, 9))
print(pw)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗493909
Result: six random digits.

