Random Numbers and Games in Python
Make Python games unpredictable with the random module: use randint, choice, shuffle and random to roll dice, pick cards and build guessing games. Beginner-friendly with runnable code, a complete game and a quiz.
Key takeaways
- import random gives you tools to make your programs unpredictable, like rolling dice
- random.randint(a, b) picks a whole number from a to b, including both ends
- random.choice(list) picks one random item from a list
- random.shuffle(list) mixes up the order of a list, like shuffling cards
- Random numbers make games fun because the computer surprises you every time
Surprise the player
What makes a game fun? Often it's not knowing what will happen next. A dice could land on any number. A card could be any card. An enemy could appear anywhere. To build games like this, your program needs to make random choices — and Python has a whole toolbox for exactly that, called the random module.
In this lesson you'll learn to roll dice, pick random items, shuffle lists, and build a complete guessing game. If you can already write your first Python program, you're ready to go.
Turning on the magic: import random
The random tools don't load by themselves. You switch them on with one line at the top of your program:
import random
import tells Python "go and fetch the random module so I can use it." After this line, you can call any random function by writing random. followed by its name. Forget the import and Python will complain that it doesn't know what random is.
Rolling dice with randint
The most useful tool for games is randint. It picks a whole number between two values — and both ends are included:
import random
roll = random.randint(1, 6)
print("You rolled a", roll)
random.randint(1, 6) can give you 1, 2, 3, 4, 5 or 6 — exactly like a real dice. Run the program a few times and you'll get different numbers. Want a twenty-sided dice? Use random.randint(1, 20). Want a coin? random.randint(0, 1) gives 0 or 1.
The "both ends included" rule is important. Some random tools stop just before the top number, but randint does not — so randint(1, 6) really can land on 6.
Picking from a list with choice
Sometimes you don't want a number — you want the computer to pick one thing from a set of options. That's random.choice:
import random
colours = ["red", "green", "blue", "yellow"]
picked = random.choice(colours)
print("The computer chose", picked)
answers = ["Yes", "No", "Maybe", "Ask again later"]
print("Magic 8 ball says:", random.choice(answers))
random.choice(colours) reaches into the list and grabs one item at random. This is perfect for a magic 8-ball, a random superhero generator, or choosing which question to ask in a quiz.
Shuffling with shuffle
Imagine a deck of cards. To deal a fair game you must shuffle it first. random.shuffle mixes a list into a random order:
import random
deck = ["Ace", "King", "Queen", "Jack", "10"]
random.shuffle(deck)
print(deck)
One important detail: shuffle changes the original list in place. It does not hand you a new shuffled list — it rearranges the one you gave it. So you write random.shuffle(deck) on its own line, not deck = random.shuffle(deck). (If you did the second, deck would become None, because shuffle returns nothing.)
A bonus: random() for decimals
If you ever need a random decimal between 0 and 1, use random.random():
import random
chance = random.random() # something like 0.732...
if chance < 0.5:
print("Heads")
else:
print("Tails")
This is handy when you want something to happen "half the time" or "1 in 4 times" — you compare the decimal against a threshold.
Worked example: a number-guessing game
Let's put it all together into a complete, playable game. The computer picks a secret number and you try to guess it, getting "too high" or "too low" hints.
import random
def guessing_game():
secret = random.randint(1, 100)
guesses = 0
print("I'm thinking of a number between 1 and 100.")
while True:
guess = int(input("Your guess: "))
guesses += 1
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"Correct! The number was {secret}.")
print(f"You got it in {guesses} guesses.")
break
guessing_game()
How it works:
secret = random.randint(1, 100)picks the hidden number. Because it's random, every game is different.- The
while True:loop keeps asking until you win.int(input(...))turns your typed answer into a number so it can be compared. guesses += 1counts each attempt.- The
if/elif/elsegives a hint, or — whenguess == secret— congratulates you andbreaks out of the loop.
Try playing smart: guess 50 first, then halve the range each time. You can always win in 7 guesses or fewer! That trick is called binary search.
Try it yourself
Build a dice game for two players:
import randomand write a functionroll()that returnsrandom.randint(1, 6).- In a loop that runs 3 times, roll for Player 1 and Player 2, print both rolls, and add each to a running total. Use a loop to repeat the rounds.
- After 3 rounds, compare the totals and print who won (or "It's a tie!").
- For a challenge, use
random.choice(["⚔️", "🛡️", "🏹"])to give each player a random weapon emoji each round, just for fun.
Once you're comfortable with randomness, try mixing it into a quiz — see building a quiz app in Python and use random.shuffle to ask the questions in a different order each time.
Quick quiz
Test yourself and earn XP
What do you write at the top of your program to use random tools?
import random loads the random module so you can call functions like random.randint.
What numbers can random.randint(1, 6) give you?
randint includes BOTH ends, so 1 and 6 are both possible — perfect for a dice roll.
Which function picks one random item from a list?
random.choice(my_list) returns a single random element from the list.
What does random.shuffle(deck) do?
shuffle rearranges the list itself into a random order. It changes the original list and returns None.
Why are random numbers useful in games?
Randomness means the computer's choices change every run, so the game stays fun and replayable.
FAQ
Not exactly. The random module uses a clever maths formula to produce numbers that LOOK random and are perfectly fine for games and quizzes. They are called pseudo-random. For things like security or lotteries, programmers use special stronger tools, but for fun projects random is exactly what you want.
Call random.seed(0) (any number works) at the start. Seeding fixes the starting point of the random sequence, so you get the same results each run. That makes it easy to test a game and check it behaves the same way while you fix bugs. Remove the seed line when you want surprises again.
Keep exploring
More in Coding