Random whole numbers
Games, simulations and quizzes need numbers nobody can predict: the roll of a die, the next card, the order of the questions. The standard library's random module makes them.
randint
random.randint(a, b) gives a random whole number from a to b. This program rolls a die five times:
import random
random.seed(2026)
for i in range(5):
print("You rolled", random.randint(1, 6))
You rolled 1
You rolled 3
You rolled 5
You rolled 5
You rolled 6What about the line random.seed(2026)? It makes the program pick the same "random" numbers on every run, so the output shown here is what you'll see when you run it too. Every example in these lessons that uses random numbers starts with such a line, and step 3 of this module explains how it works. Leave it out, and the numbers change on every run, which is what a real game wants.
Both ends included
Unlike range(1, 6), which stops before 6, randint(1, 6) can give 1 and 6 and everything between. Roll a thousand times and both ends turn up:
import random
random.seed(1)
rolls = []
for i in range(1000):
rolls.append(random.randint(1, 6))
print("Smallest:", min(rolls))
print("Largest:", max(rolls))
Smallest: 1
Largest: 6Using the number
A random number is an ordinary integer, so it works in calculations and conditions like any other. Here randint(0, 1) tosses a coin, and the functions come in with from, as in the previous module:
from random import randint, seed
seed(7)
for i in range(4):
if randint(0, 1) == 0:
print("Heads")
else:
print("Tails")
Tails
Heads
Tails
HeadsOne call, one number
Every call of randint gives a new number, but a variable keeps the one it was given. This program rolls the die once and prints that same roll three times:
import random
random.seed(3)
roll = random.randint(1, 6)
for i in range(3):
print(roll)
2
2
2For three different rolls, call random.randint(1, 6) inside the loop, once for each roll.