Posted on • Edited on
Introduction to the Python Random Library
Introduction
Python has a built-inrandom
library that provides various functions for performing stochastic operations. In this chapter, we'll explore some of the most commonly used functions in therandom
library, including generating random numbers, making random choices, and shuffling sequences.
Generating Random Numbers
Several functions are available to generaterandom
numbers, includingrandom
,uniform
,randint
, andrandrange
. Here's an example of using these functions to generate random numbers representing the roll of a die and the toss of a coin:
importrandom# Generate a random integer between two valuesmin_die=1max_die=6die_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 sequencecoin_toss=random.choice(seq=["heads","tails"])print(f"Coin toss:{coin_toss}")
Output:Coin toss: tails
Making Random Choices
Thechoice
andchoices
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:
importrandomcards=["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]# Make a random choice from a sequencecard=random.choice(seq=cards)print(f"Randomly selected card:{card}")
Output:Randomly selected card: 7
# Make multiple random choices from a sequencenum_choices=5cards=random.choices(population=cards,k=num_choices)print(f"Randomly selected cards:{cards}")
Output:Randomly selected cards: ['Queen', '3', 'King', '9', '8']
Shuffling Sequences
Theshuffle
function is available to shuffle a sequence in place randomly. Here's an example of using theshuffle
function to randomly shuffle a list of cards:
importrandomcards=["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]# Shuffle a sequence in placerandom.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, therandom
library is an essential tool for any Python programmer.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse