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.
- Raffles
sample()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
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.
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))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.
- import random
- random.seed(42)
- roll = random.randint(1, 6)
- deck = ["A", "K", "Q"]
- random.shuffle(deck)
- pick = random.choice(deck)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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)
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
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.
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)Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
import random deck = [1, 2, 3] deck = random.shuffle(deck) print(deck)
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Product design
Splitting test users into groups
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
samplewith 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.Pythonimport 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))OutputPress 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?
Why does my program give different results each time?
How do I pick a random item from a dictionary?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.