Let Python roll the dice
The problem...
Every program you've written so far is predictable. Same input — same output. Every time.
But real programs aren't always like that. Games. Simulations. Security. Testing. All of them need values you didn't choose.
You need Python to surprise you.
The idea!
Python has a built-in module called random. It generates values you can't predict — numbers, choices, outcomes. You set the boundaries. Python picks.
Importing random
import random
One line at the top of your file. That's all. import loads a module — a collection of ready-made tools. You'll learn more about modules in the Functions chapter. For now — just write it and move on.
randint() — a random integer
import random
number = random.randint(1, 10)
print(number) # different every time
randint(1, 10) gives you a random integer between 1 and 10. Both ends included. Run it ten times — ten different results.
Simulating a dice roll
import random
roll = random.randint(1, 6)
print(f"You rolled: {roll}")
Six possible outcomes. Python picks one. You don't control which.
choice() — pick from a sequence
import random
word = "Bull"
letter = random.choice(word)
print(f"Random letter: {letter}")
choice() picks one item from a sequence at random. A string, a range — anything Python can move through.
Using random with what you know
import random
for i in range(5):
roll = random.randint(1, 6)
print(f"Roll {i + 1}: {roll}")
# Roll 1: 4
# Roll 2: 1
# Roll 3: 6
# Roll 4: 2
# Roll 5: 5
Five rolls. Five different results. The loop is predictable — the values inside it aren't.
Heads up!
import randomgoes at the top of your file — alwaysrandint(a, b)— bothaandbare includedchoice(sequence)— picks one item at random- Every run gives different results — that's the point
The mindset shift
Stop thinking: "I control every value."
Start thinking: "I control the boundaries. Python fills in the surprise."
What you should understand now
import randomloads the random modulerandom.randint(a, b)— random integer, both ends includedrandom.choice(sequence)— random item from a sequence- Random values make programs unpredictable — and useful