A random number comes from a process whose exact result cannot be predicted in advance. Python’s random library uses a pseudo-number generator to add uncertainty to programs, such as choosing list items, rearranging data, or simulating chance. section 35.3
Common random-number operations include:
- Generate a floating-point value from 0, including 0, up to but not including 1 with random.random(). section 35.3
- Generate an integer within inclusive bounds with random.randint(a, b). section 34.1
- Choose one item from a list with random.choice(), or choose several without repeating an item with random.sample(). section 35.3
- Repeat a random sequence for testing by setting a seed before generating values. section 35.3
Simulating a game of chance
In rock-paper-scissors, random.random() returns a value between 0 and 1. Dividing that range into three intervals lets the program select rock, paper, or scissors with an approximately equal chance. The program then compares the computer’s choice with the player’s input. section 35.3
Random positions and sizes
A graphical tag game can use random.randint() to choose a player rectangle’s size and top-left coordinates. Adding the size to those coordinates produces the opposite corner, so each new player appears in a different position and size. section 38.2
Listing 35.2. Using the random library to play rock-paper-scissors
import random #1
choice = input("Choose rock, paper, or scissors: ")
r = random.random() #2
if r < 1/3: #3
print("Computer chose rock.")
if choice == "paper":
print("You win!")
elif choice == "scissors":
print("You lose.")
else:
print("Tie.")
elif 1/3 <= r < 2/3: #4
print("Computer chose paper.")
if choice == "scissors":
print("You win!")
elif choice == "rock":
print("You lose.")
else:
print("Tie.")
else: #5
print("Computer chose scissors.")
if choice == "rock":
print("You win!")
elif choice == "paper":
print("You lose.")
else:
print("Tie.")
Walk through a complete rock-paper-scissors example that turns a random value into one of three computer choices. section 35.3



