Python Random
Games roll dice, quizzes shuffle questions, simulations pick random samples. Python's random module produces random numbers and makes random choices. The numbers come from a formula, so they are called pseudo-random: they look random, and for games and simulations they are, but they can be repeated exactly when you want.
Random numbers
import random
dice = random.randint(1, 6) # a whole number from 1 to 6
fraction = random.random() # a float from 0 up to 1
temperature = random.uniform(20, 30)
print(1 <= dice <= 6, 0 <= fraction < 1, 20 <= temperature <= 30)True True True
randint(a, b) includes both ends, unlike range. random() gives a float that can be 0 but is always below 1, and uniform(a, b) a float between two values. The example prints only checks, because the numbers themselves change every time you run it; run it in the editor and print the numbers to see them.
Random choices
import random
colours = ["red", "green", "blue", "yellow"]
print(random.choice(colours) in colours)
hand = random.sample(range(1, 53), 5) # 5 different cards
print(len(hand), len(set(hand)))
deck = list(range(1, 11))
random.shuffle(deck)
print(sorted(deck) == list(range(1, 11)))True 5 5 True
choice picks one item. sample picks several different items, while choices(items, k=3) may pick the same item more than once. shuffle mixes a list in place and returns None.
Repeatable results with a seed
Giving the generator a seed makes it produce the same sequence every time. That is useful for testing, and for sharing a simulation that others can repeat:
import random
random.seed(2026)
first = [random.randint(1, 100) for _ in range(5)]
random.seed(2026)
second = [random.randint(1, 100) for _ in range(5)]
print(first == second)
print(first)True [16, 41, 65, 66, 83]
Run it twice: the list is always the same, because the seed is the same.
Passwords and security
Do not use random for passwords, tokens or anything secret: its sequence can be predicted. The secrets module uses the operating system's secure randomness instead, for example secrets.token_hex(8) or secrets.choice(alphabet).
Practice exercises
- Simulate rolling two dice ten times and print each total.
- Pick a random winner from a list of names with
choice. - Shuffle the numbers 1 to 10 and print them.
- Write a number guessing game where the computer picks a secret number from 1 to 50.