Introduction
Python has a built-in random
library that provides various functions for performing stochastic operations. In this chapter, we'll explore some of the most commonly used functions in the random
library, including generating random numbers, making random choices, and shuffling sequences.
Generating Random Numbers
Several functions are available to generate random
numbers, including random
, uniform
, randint
, and randrange
. Here's an example of using these functions to generate random numbers representing the roll of a die and the toss of a coin:
import random
# Generate a random integer between two values
min_die = 1
max_die = 6
die_roll = random.randint(a=min_die, b=max_die)
print(f"Die roll: {die_roll}")
Output:
Die roll: 4
# Generate a random choice from a sequence
coin_toss = random.choice(seq=["heads", "tails"])
print(f"Coin toss: {coin_toss}")
Output:
Coin toss: tails
Making Random Choices
The choice
and choices
functions are available to make random selections from a sequence. Here's an example of using these functions to randomly select a card from a deck of cards:
import random
cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
# Make a random choice from a sequence
card = random.choice(seq=cards)
print(f"Randomly selected card: {card}")
Output:
Randomly selected card: 7
# Make multiple random choices from a sequence
num_choices = 5
cards = random.choices(population=cards, k=num_choices)
print(f"Randomly selected cards: {cards}")
Output:
Randomly selected cards: ['Queen', '3', 'King', '9', '8']
Shuffling Sequences
The shuffle
function is available to shuffle a sequence in place randomly. Here's an example of using the shuffle
function to randomly shuffle a list of cards:
import random
cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
# Shuffle a sequence in place
random.shuffle(x=cards)
print(f"Shuffled cards: {cards}")
Output:
Shuffled cards: ['3', 'Queen', '8', '2', 'King', 'Jack', 'Ace', '9', '6', '7', '10', '5', '4']
Conclusion
Whether you're simulating a game of chance or generating random data for a machine-learning model, the random
library is an essential tool for any Python programmer.
Top comments (0)