Randomness and games in Python
Be able to use random to simulate dice and to build a guessing game.
Prerequisites
Intuition
The random module gives random numbers:
import random
random.randint(1, 6) # a whole number 1–6, like a die
random.random() # a decimal 0–1
random.choice(["rock", "scissors", "paper"])
random.shuffle(items) # shuffles the list in place
Seeding: random.seed(42) makes the randomness predictable — the same numbers every run. It sounds like a contradiction, but it is invaluable when you are debugging or when you want someone else to get exactly the same result.
Code
import random
def guessing_game(max_number=100, seed=None):
if seed is not None:
random.seed(seed)
secret = random.randint(1, max_number)
attempts = 0
while True:
guess = int(input(f"Guess 1–{max_number}: "))
attempts += 1
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
else:
print(f"Right, in {attempts} attempts!")
return attempts
# simulate 10 000 dice rolls and count the sixes
random.seed(0)
rolls = [random.randint(1, 6) for _ in range(10_000)]
print(rolls.count(6) / 10_000) # ≈ 0.167
Simulation is a way of testing probabilities without formulas: run it enough times and count.
Mastery means
- Uses random to simulate random trials
- Builds a small game with a loop, a condition and a counter
Sign in to do the exercises and build your mastery up.