Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Dice, Luck & random (with a Seed)

12 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 2 of 5 · View course roadmap
Step 1

Learn the idea

Games need luck, and Python's random module provides it: random.randint(1, 6) is a die roll. But there's a professional secret hiding here:

random.seed(n) makes randomness repeatable. Seed the generator and the "random" sequence is exactly the same every run. That sounds like cheating — it's actually how games are tested, how Minecraft shares worlds (a world is a seed), and how scientists make simulations reproducible.

  • random.randint(a, b) — whole number from a to b, inclusive
  • random.choice(items) — pick one item from a list
  • random.seed(n) — same seed → same sequence, every time

Where you'll use this

Seeded randomness runs the world's simulations: game worlds (a Minecraft world is a seed), scientific Monte-Carlo models, and every automated test of 'random' behaviour. Reproducible luck is a professional tool.

Common mistakes

  • Calling random.seed() inside the loop — that restarts the sequence and every 'roll' becomes identical.
  • Expecting randint(1, 6) to exclude 6 — unlike range(), it includes both endpoints.
  • Rolling one die and doubling it: 2 * randint(1, 6) can never produce 7 and has completely different odds from two real dice.

Pro tip

random.choice(list) and random.shuffle(list) cover most game needs without index math — picking a random enemy is one readable line.

Step 2

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +25 XP

Blank · autosaved

Seed the generator with random.seed(1), then roll two dice three times. For each round print Roll N: A + B = total (roll both dice with randint(1, 6), first die first).

Target output
Roll 1: 2 + 5 = 7
Roll 2: 1 + 3 = 4
Roll 3: 1 + 4 = 5
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does random.seed(1) guarantee?
2. random.randint(1, 6) can return…
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path