One-sentence summary
Using Python's random module, we learn to write small programs that roll a die and play rock-paper-scissors, and we see how randomness creates a fair surprise in games.
Why does it matter?
Most of the games you enjoy contain things you cannot predict. What number will the die show? Which reward will the card reveal? From which direction will the enemy appear? This uncertainty is what makes games fun. If everything were known in advance, a game would get boring quickly.
Computers are actually very orderly: given the same command, they produce the same result every time. So where does the surprise come from? This is where randomness enters. Randomness means producing a result that we cannot know for certain in advance.
Python has a ready-made tool for this: the random module. In this lesson we will use it to write a real die and a real round of rock-paper-scissors. We will also talk about the idea of "fair randomness," meaning that every outcome should have an equal chance.
Getting to know the random module
In Python, some ready-made tools sit in separate boxes. These boxes are called modules. The box that works with random numbers is named random. Before using it, we call it once at the top of the program.
import random
The word import means "bring this module into my program." Writing it once is enough; you can then use the random tools anywhere in that file.
randint: a whole number in a range
randint (random integer) picks a random whole number between two limits. Both limits are included in the choice.
import random
number = random.randint(1, 6)
print(number)
This program prints a random number between 1 and 6 (including 1 and 6). Each time you run it you may see a different result, just like a die.
choice: a random pick from a list
Sometimes you do not need a number but one of several ready options. choice looks at a list and picks one element from it at random.
import random
colors = ["red", "green", "blue"]
pick = random.choice(colors)
print("Chosen color:", pick)
Here the program picks one of the three colors at random. You can add as many options to the list as you like.
Short definition:randint(a, b)gives a random whole number between a and b;choice(list)gives a random element from a list.
Example 1: A dice-rolling program
Now let's write a small dice program with randint. Let the user roll each time they press Enter.
import random
print("Press Enter to roll the die.")
input()
die = random.randint(1, 6)
print("The die shows", die)
Run the program and try it a few times. Each time you get a number between 1 and 6, and you cannot know beforehand which one will appear.
Two dice at once
Many games use two dice instead of one. Let's make two separate calls and print their sum.
import random
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
total = die1 + die2
print("First die:", die1)
print("Second die:", die2)
print("Total:", total)
The sum of two dice falls between 2 and 12. The most common total is 7, because many combinations add up to 7. Randomness is still fair here: each die on its own has an equal chance.
Example 2: A round of rock-paper-scissors
Now let's use choice to write a round where the user plays against the computer. First we set the computer's choice at random.
A reminder about indentation
In Python, the lines under if, elif and else blocks are written 4 spaces to the right. This indentation shows Python which line belongs to which condition. If you forget the indentation, the program raises an error.
The computer's choice
import random
options = ["rock", "paper", "scissors"]
computer = random.choice(options)
player = input("Your choice (rock/paper/scissors): ")
input takes the text the user types. The user cannot see the computer's choice, which keeps the game fair.
Finding the winner
Now let's write the rules with if/elif/else. The same choice is a tie; we check the remaining cases one by one.
if player == computer:
result = "It's a tie!"
elif player == "rock" and computer == "scissors":
result = "You win!"
elif player == "paper" and computer == "rock":
result = "You win!"
elif player == "scissors" and computer == "paper":
result = "You win!"
else:
result = "You lose!"
print("Computer:", computer)
print(result)
and requires both conditions to be true at the same time. For example, rock beats only scissors. If the user matches none of these three winning cases (else), the result is a loss.
The idea of fair randomness
random.choice picks each option with an equal chance: rock, paper and scissors each have a one-in-three probability. That is what fair randomness means. No option has an advantage over another.
To keep a game fair:
- The computer's choice must not be made after looking at the user's choice. Otherwise the computer always wins, and that is cheating.
- Each option must appear an equal number of times in the list. If you write
["rock", "rock", "paper", "scissors"], rock appears more often and the game is no longer fair.
Fair randomness keeps a game both fun and trustworthy.
Mini practice
Turn the dice game into a small contest. The user and the computer each roll one die; the higher number wins.
import random
you = random.randint(1, 6)
computer = random.randint(1, 6)
print("Your die:", you)
print("Computer's die:", computer)
if you > computer:
print("You win!")
elif you < computer:
print("You lose!")
else:
print("It's a tie!")
Experiments:
- Run the program 5 times and count how many times you win.
- Change the die to
randint(1, 12)to make a twelve-sided die. - Put the rock-paper-scissors round inside a
whileloop so it keeps playing until the user types "quit."
Common mistakes
Forgetting the import line
If you do not write import random before using random, Python raises a "random is not defined" error. This line must appear once at the top of the file.
Misreading the randint limits
random.randint(1, 6) includes both 1 and 6 in the result. Some students think 6 will never appear; in fact, for a six-sided die that is exactly correct.
Mixing up indentation
If you do not indent the lines under an if block, or use uneven spacing, the program raises an IndentationError. Use 4 spaces for each block.
Using a single equals sign in a comparison
To check for equality you use ==. A single = is for assignment. If you write if player = computer: you get an error; the correct form is if player == computer:.
Safety note
All of the programs in this lesson are harmless games that run on your own computer. Even so, as a general habit, only run code that you wrote yourself or that you trust. Do not write a game that asks for your real name, address or password, and do not enter your personal information into programs.
Lesson summary
- The
randommodule adds randomness to Python and is brought in withimport random. randint(a, b)gives a random whole number between a and b (both included); it is ideal for rolling dice.choice(list)picks a random element from a list; it is used for rock-paper-scissors.- In game logic we turn the winner into decision rules with
if/elif/else. - In fair randomness every option has an equal chance and the computer does not cheat by looking at the user's choice.
Check questions
- Which line must we write at the top of the program before using the
randommodule? - What is the smallest and the largest number
random.randint(1, 6)can produce? - Which function do we use to pick a random element from a list?
- When does a tie happen in rock-paper-scissors?
- If we use
choicewith the list["rock", "rock", "paper", "scissors"], why is the game not fair?
Answers
- We must write the line
import random. - It can produce a smallest value of 1 and a largest value of 6; both limits are included.
- We use the
random.choicefunction. - A tie happens when the user's choice and the computer's choice are the same.
- Because rock appears twice in the list, it is chosen more often; since the options do not have an equal chance, the randomness is not fair.
Source and verification note
For “Randomness and Simple Game Logic”, verification focuses on whether the relationship between Getting to know the random module and choice: a random pick from a list remains consistent across examples. Code examples follow Python 3 syntax. Small differences may appear between environments, so examples should first be tested in a safe online editor or a local development setup.
Next lesson
Modules and Libraries: We explore how we bring ready-made modules into our own programs and what Python's standard library offers us.