Skip to contentSkip to navigation

Module 11 · Lesson 03

Random Numbers and Secrets

Add chance to programs with the random module: random numbers, choices, samples and shuffles, repeatable results with seed, and the secrets module for passwords and tokens.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Roll and pick
  • Shuffle and sample
  • Repeat with seed
  • Watch a seeded game

Controlled chance

`random` rolls dice, deals cards and shuffles lists. `secrets` makes codes nobody can guess.

  • Numbers

    randint(1, 6) gives a whole number with both ends included. random() gives a decimal from 0 up to 1.

  • Picking

    choice() picks one item, sample() several without repeats, choices() several with repeats.

  • Shuffle

    shuffle(cards) mixes the list itself and returns None.

  • seed

    seed(42) gives the same "random" results on every run, which is handy for testing.

Chance everywhere

Games, music apps and science all use random numbers.

  • GamesDice rolls, loot drops and enemy moves all use random numbers.
  • Shuffle playA music app shuffles the queue so songs come in a new order.
  • SimulationsRoll a die thousands of times to see how often each number comes up.
  • Rafflessample() picks three different winners from the tickets.

Picking raffle winners

This line picks three different winners. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

result:A new list of 3 tickets. The original list is untouched.

Roll, pick and shuffle

Pick an example and press Run a few times. Most results change on every run; that is the point.

Example 1 of 6Roll dice

randint(a, b) includes both ends. Run it a few times.

Your turn: Roll a 20-sided die.

Python
import random
print("Die:", random.randint(1, 6))
print("Two dice:", random.randint(1, 6) + random.randint(1, 6))
print("Coin:", random.choice(["heads", "tails"]))
print("Decimal:", round(random.random(), 3))
Output
Press Run to see what it prints.

Watch a seeded game

Press Step to run one line at a time. The seed makes these "random" results the same on every run.

Ready. Press Step to run the first line.

  1. import random
  2. random.seed(42)
  3. roll = random.randint(1, 6)
  4. deck = ["A", "K", "Q"]
  5. random.shuffle(deck)
  6. pick = random.choice(deck)
  7. print(roll, deck, pick)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.How many picks come back?

import random
print(len(random.choices("ab", k=5)))

0 of 6 answered

Common randomness misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Random numbers

Try it 1: edit me, then Run
import random

print(random.randint(1, 6))       # a dice roll: 1, 2, 3, 4, 5 or 6
print(random.random())            # a float from 0.0 up to, not including, 1.0
print(random.uniform(1.5, 2.5))   # a float between 1.5 and 2.5
Output
Press Run to see what it prints.

randint(a, b) includes both ends, which makes it natural for dice. randrange(start, stop, step) works like range and leaves out the stop value, so randrange(0, 100, 5) gives a multiple of 5 from 0 to 95. Each call gives a new value; run the program again and you get different ones.

Choosing from a list

Try it 2: edit me, then Run
colours = ["red", "green", "blue", "yellow"]
print(random.choice(colours))           # one item
print(random.sample(colours, 2))        # two different items
print(random.choices(colours, k=5))     # five picks, repeats allowed
Output
Press Run to see what it prints.

The difference between the last two is important. sample draws without replacement, like drawing raffle tickets out of a hat: each item can be picked once, so k cannot be larger than the list. choices draws with replacement, like rolling a die several times: the same item can come up again.

choices can also be weighted, so some items come up more often than others:

Try it 3: edit me, then Run
prize = random.choices(["nothing", "sticker", "jackpot"], weights=[80, 19, 1], k=1)[0]
Output
Press Run to see what it prints.

Here "nothing" is 80 times as likely as the jackpot. The weights do not have to add up to 100; only their sizes relative to each other matter. Note that choices always returns a list, even for a single pick.

Shuffling

random.shuffle(items) puts a list into a random order in place. Like list.sort(), it changes the list and returns None, so deck = random.shuffle(deck) is a bug that leaves you with None. To keep the original, shuffle a copy, or use random.sample(items, len(items)), which returns a new shuffled list.

Repeatable randomness with seed

The numbers from random are pseudo-random: they come from a formula that produces a sequence which looks random. The starting point of that sequence is called the seed. Normally Python picks a different seed each run. Setting it yourself makes the whole sequence repeat exactly:

Try it 4: edit me, then Run
random.seed(42)
first = [random.randint(1, 6) for _ in range(5)]
random.seed(42)
second = [random.randint(1, 6) for _ in range(5)]
print(first == second)            # True
Output
Press Run to see what it prints.

Seeding is invaluable for testing and for sharing results: a bug in a card game that only appears on one shuffle can be replayed with the same seed. The examples in this lesson set a seed so their output is the same every time you run them. In a real game you would leave the seed out, so every game is different.

The underscore in for _ in range(5) is a common name for a loop variable that is not used.

Simulations

Repeating a random experiment many times estimates how likely an outcome is. How often do two dice add up to 7?

Try it 5: edit me, then Run
random.seed(1)
trials = 10_000
sevens = sum(1 for _ in range(trials) if random.randint(1, 6) + random.randint(1, 6) == 7)
print(round(sevens / trials, 2))  # close to 1/6, about 0.17
Output
Press Run to see what it prints.

This Monte Carlo approach is used for everything from weather forecasts to financial risk. More trials give a better estimate, at the cost of more time. The underscore in 10_000 is only there to make the number easier to read.

Never use random for secrets

The random module is predictable. Its sequence is designed to be fast and to look random, not to resist attack. Someone who sees enough outputs can work out the internal state and predict every future value. That is fine for dice, but it would let an attacker guess a password reset code or a session token.

For anything security-related, use the secrets module, which draws from your operating system's secure source of randomness:

Try it 6: edit me, then Run
import secrets
import string

token = secrets.token_hex(16)            # 32 random hexadecimal characters
pin = secrets.randbelow(10_000)          # 0 to 9999
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(12))
Output
Press Run to see what it prints.

secrets has no seed: its whole point is that its output cannot be reproduced. Use it for passwords, tokens, invitation codes and anything else a stranger must not be able to guess.

Testing random code

Random behaviour seems hard to test, but two techniques help. Seed the generator, so a test sees the same values each time. Or test the properties that must always hold, whatever the random values: a dice roll is always from 1 to 6, a shuffled deck still has 52 different cards, a sample never contains duplicates. Property checks like these catch real bugs, such as an off-by-one that can produce a 7.

Syntax

The general shape of the statements in this lesson.

syntax.py
import random
random.randint(1, 6)            # 1..6, both ends included
random.randrange(0, 10, 2)      # like range: 0, 2, 4, 6 or 8
random.random()                 # 0.0 <= x < 1.0
random.uniform(a, b)            # float between a and b
random.choice(items)            # one item
random.sample(items, k)         # k different items
random.choices(items, weights=w, k=n)   # n picks, with repeats
random.shuffle(items)           # in place, returns None
random.seed(42)                 # repeatable sequence
import secrets                  # for passwords and tokens
secrets.token_hex(16); secrets.choice(alphabet)
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A fair raffle draw

Beginner

Draw three different winners from a list of entrants, with first, second and third place, and show that the same seed gives the same result so the draw can be audited.

Python
import random

entrants = ["Ana", "Ben", "Cy", "Dee", "Eli", "Fay", "Gus"]

def draw(names, seed):
    random.seed(seed)
    return random.sample(names, 3)

winners = draw(entrants, seed=2024)
for place, name in zip(["1st", "2nd", "3rd"], winners):
    print(place, name)

print("Replay matches:", draw(entrants, seed=2024) == winners)
print("Different winners:", len(set(winners)) == 3)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

sample never picks the same person twice, which is what a raffle needs. Publishing the seed lets anyone repeat the draw and confirm the result. In a live draw the seed would be chosen in public, for example by rolling dice.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Assigning the result of shuffle

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
import random
deck = [1, 2, 3]
deck = random.shuffle(deck)
print(deck)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints None, and the deck is lost

Write this instead

import random
deck = [1, 2, 3]
random.shuffle(deck)
print(deck)

Why it happens

shuffle changes the list in place and returns None, like list.sort().

In the real world

Where this shows up in software people use every day.

  1. Splitting test users into groups

    Product design

    A team testing a new checkout page shows it to a random half of users and the old page to the rest, then compares how many in each group complete a purchase. A fixed seed makes the split reproducible for the analysts.

    Why Python fits

    sample with the full length returns a shuffled copy, so the original user list is untouched. Splitting it in half gives two random, equal groups. The final check is a property test: whatever the shuffle, every user must appear exactly once.

    Python
    import random
    
    users = [f"user{n}" for n in range(1, 11)]
    random.seed(99)
    shuffled = random.sample(users, len(users))
    half = len(shuffled) // 2
    groups = {"new page": sorted(shuffled[:half]), "old page": sorted(shuffled[half:])}
    
    for name, members in groups.items():
        print(name, len(members), members[:3])
    print("Everyone placed once:", sorted(groups["new page"] + groups["old page"]) == sorted(users))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Are computer random numbers truly random?

The random module's numbers come from a formula, so they are pseudo-random. They are random enough for games and simulations. secrets uses the operating system's secure source, which mixes in unpredictable events.

Why does my program give different results each time?

Without a seed, Python starts the sequence from a different point each run. Call random.seed(any_number) at the start to make runs repeat.

How do I pick a random item from a dictionary?

Pick from its keys: random.choice(list(prices)). choice needs a sequence that supports indexing, so convert the keys to a list first. The same applies to a set.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 12 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.