TwiddleLab / Code / Build with Python
Randomness and Simulation
What you will learn
- import random, then random.randint(a, b) gives a whole number from a to b, both ends included.
- A simulation repeats a random experiment many times and counts: with enough tries the share settles near the real chance.
- The sum of two dice peaks at 7: more ways to make it.
- random.seed(n) makes the same random numbers every run, so tests can check the answer.
How the lesson goes
Is a die really 1 in 6?
Roll it 10 times and watch the bars.
Now roll two dice and add them. Draw the bars you expect.
Sums go from 2 to 12. Press and drag across the chart.
Slide from 10 rolls to 10,000.
One die first, then the sum of two. Your drawing is dashed on the two-dice chart.
Randomness in Python.
import random brings in Python's random tools. random.randint(a, b) gives a whole number from a to b, both included. random.choice(list) picks one item.
A simulation runs a random experiment many times and counts what happened. The share of hits settles near the true chance.
random.seed(n) fixes the starting point, so the same 'random' numbers come out every run.
Six rolls, counting sixes.
Run it, then Reset and run it again. Compare the rolls.
Build a coin flipper: count heads in 1000 flips.
randint(0, 1) is a coin: 1 means heads.
Roll a die 4 times. What's the chance of at least one 6?
Pin your estimate, then let 10,000 simulated games answer.
Run each program twice. Which one could a test check?
A test compares the output with the answer it expects.
One of these coins is loaded. Find it with your flipper.
Each flip costs from a budget of 2000. Flip, compare, then accuse.
Speed round: seed it, or keep it truly random?
Drop each situation in its box.
Previous lesson: Functions That Call Functions · Next lesson: Grids: Lists of Lists · Part of the course: Build with Python
Lessons are interactive and need JavaScript. Turn it on to play them.