The crew plays a two-dice game at lunch, and they argue about which total comes up most. Rocket says 12. Raven is not so sure.
"We could roll two dice a thousand times and write down every total," Rocket says. "That would take all week."
Raven smiles and opens her notebook to a fresh page. "What do you notice?" she asks. "Rolling and counting is a loop and a dictionary. We know both."
Nova spins up a cloud of tiny glowing dice. "Interesting," she says. "A computer can roll a thousand pairs in less than a second. That is called a simulation."
Rocket cracks open the editor, eager to settle the argument.
# two_dice.py
import random
counts = {}
for roll in range(1000):
total = random.randint(1, 6) + random.randint(1, 6)
counts[total] = counts.get(total, 0) + 1
for total in range(2, 13):
print(f"{total:2d}: {counts.get(total, 0)}") Each run gives slightly different counts, so there is no single right output. But the shape is the same every time: the middle totals come up far more often than 2 or 12.
The :2d makes each total take two spaces, so the colons line up.
The tool random.shuffle(a_list) mixes a list into a random order, like shuffling cards.
The tool random.sample(a_list, 2) picks 2 different items and leaves the list unchanged.
# shuffle_crew.py
import random
jobs = ["pilot", "navigator", "engineer", "medic"]
random.shuffle(jobs)
print("Job order:", jobs)
print("Two inspectors:", random.sample(jobs, 2))
print("Still", len(jobs), "jobs") Here is a smaller simulation. It flips a coin 100 times and counts the heads. Each run differs, but some things are always true.
# coin_flips.py
import random
heads = 0
for flip in range(100):
if random.choice(["heads", "tails"]) == "heads":
heads = heads + 1
print("Heads:", heads)
print("Tails:", 100 - heads) | Statement | True or false? |
|---|---|
| A simulation uses many random trials to answer a question. | ? |
| random.shuffle changes how many items a list has. | ? |
| random.sample(jobs, 2) picks two different items. | ? |
| More trials usually give a clearer pattern. | ? |
You ran your first simulation and let the data answer a question. Tomorrow you will build a quiz that shuffles its questions.