Randomness and Chance: The random Module
Teach your programs to roll dice, flip coins, and surprise you
random module is a built-in Python toolbox for making unpredictable choices. With one line, import random, your programs can roll a die, flip a coin, shuffle a deck of cards, or pick a secret number for a guessing game.
- bring in the toolbox with
import random, - get a whole number with
random.randint(a, b), - pick one item from a list with
random.choice(seq), - mix up a list with
random.shuffle(list), - get a decimal between 0 and 1 with
random.random(), - use these to build dice, coin flips, card draws, and a guessing game.
1. Why do programs need randomness?
Computers are famous for doing the exact same thing every time. That is wonderful for a calculator, but boring for a game. A dice game where the die always shows 4 is no fun at all!
The random module gives your programs a pinch of surprise. Think of it like a bag of numbered ping-pong balls: you reach in without looking and pull one out. You cannot predict which one you will get, and that is exactly the point.
Because random comes built into Python (it is part of the standard library you met earlier), you do not install anything. You just borrow it with one line at the top of your program:
import random
After that line, every tool lives behind the word random followed by a dot. So you write random.randint(...), random.choice(...), and so on. The dot means "reach inside the random toolbox and use this tool."
2. random.randint(a, b) — a whole number
random.randint(a, b) gives you a random whole number (an integer) between a and b. The most important thing to remember: both ends are included. So random.randint(1, 6) can give any of 1, 2, 3, 4, 5, or 6 — just like a real six-sided die.
import random
roll = random.randint(1, 6)
print("You rolled a", roll)
Possible output (it changes each run):
You rolled a 4
Run it again and you might see 1, or 6, or anything in between. The number is chosen fresh every time.
Remember: the second number is included. A common mistake is thinking randint(1, 6) stops at 5. It does not — 6 is a real possibility.