Project: is the dice fair?
Section 11: Randomness and errorsLesson 11.2 · ⏱ 10 min
🎯 Project goal
We roll the dice 6000 times, count every face in a dictionary, and draw a bar of # for each face.
Predict before running: if the dice is fair, about how many times does each face appear?
import random
counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
for i in range(6000):
face = random.randint(1, 6)
counts[face] += 1
for face in counts:
print(face, counts[face], "#" * (counts[face] // 50))
print("total:", sum(counts.values()))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗1 1039 #################### 2 1020 #################### 3 1001 #################### 4 968 ################### 5 953 ################### 6 1019 #################### total: 6000

🖥️ What happens on the stage?
The numbers change with every run, but they stay close to 1000 for each face. That is what a fair dice means.
- Roll two dice together and add them, and count the results from 2 to 12. Which sum appears most? And why?
📌 Another example: a coin: heads or tails?
We toss the coin 1000 times and count.
import random
heads = 0
for i in range(1000):
if random.choice(["heads", "tails"]) == "heads":
heads = heads + 1
print("heads:", heads)
print("tails:", 1000 - heads)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗heads: 496 tails: 504
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Roll the dice 10 times and print the results in a list.
👀 Show the solution🙈 Hide the solution
import random
rolls = []
for i in range(10):
rolls.append(random.randint(1, 6))
print(rolls)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗[6, 4, 4, 6, 3, 4, 6, 3, 3, 1]
Result: a list of 10 numbers between 1 and 6.
Medium
How many times do we roll the dice until a 6 appears?
👀 Show the solution🙈 Hide the solution
import random
count = 0
while True:
count = count + 1
if random.randint(1, 6) == 6:
break
print("6 after", count, "rolls")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗6 after 1 rolls
Result: a different number every time.
Hard
Two dice together 1000 times: how many times was the sum 7?
👀 Show the solution🙈 Hide the solution
import random
sevens = 0
for i in range(1000):
if random.randint(1, 6) + random.randint(1, 6) == 7:
sevens = sevens + 1
print("sevens:", sevens)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗sevens: 180
Result: about 167 times: seven is the sum that comes up most.

