In this post, we will learn how to generate random numbers in Python. We will explore the Python random
module and its various functions to generate random numbers, providing detailed explanations and examples. So, let’s start learning!
You can also checkout Our previous article 👉 Python Math Module With Example
Random Module
The random
module is a built-in Python module that provides several functions to generate random numbers. To use the random
module, you just need to import it into your program, and then you can use its functions to generate random numbers in Python.
import random
Now let’s explore important functions of the random
module that are used to generate random numbers.
random.random()
The random.random()
function generates a random floating-point number between 0.0 and 1.0 (inclusive of 0.0, but not 1.0).
import random
print(random.random()) # 0.8474337369372327
This function generate random number each time between 0.0 to 1.0.
random.randint(a, b)
The random.randint(a,b)
generate a random integer between a
and b
(including both a
and b
).
import random
print(random.randint(1, 10)) # 5
This function is very helpful and is also one of the most used functions of the random
module. You can use it to create survival games, such as a number guessing game or a dice roller.
Example
Let’s Create simple dice roller game using random.randint()
function.
import random
def roll_dice():
# Generate a random number between 1 and 6
return random.randint(1, 6)
def play_dice_roller():
print("Welcome to the Dice Roller Game!")
while True:
# Ask the user if they want to roll the dice
roll = input("Press 'r' to roll the dice, or 'q' to quit: ").lower()
if roll == 'r':
# Roll the dice and display the result
dice_value = roll_dice()
print(f"You rolled a {dice_value}!")
elif roll == 'q':
# Exit the game
print("Thanks for playing! Goodbye!")
break
else:
print("Invalid input. Please press 'r' to roll or 'q' to quit.")
# Start the game
play_dice_roller()
Output:
Welcome to the Dice Roller Game!
Press 'r' to roll the dice, or 'q' to quit: r
You rolled a 4!
Press 'r' to roll the dice, or 'q' to quit: r
You rolled a 2!
Press 'r' to roll the dice, or 'q' to quit: r
You rolled a 6!
Press 'r' to roll the dice, or 'q' to quit: q
Thanks for playing! Goodbye!
The entire game is based on just one function, random.randint
, which demonstrates the power of this function.
random.uniform(a, b)
The random.uniform(a,b)
generate a random floating-point numbers between a
and b
(including both a
and b
).
import random
print(random.uniform(1.5, 10.5)) # 7.2367
random.choice(sequence)
When you need to select a random item from a list, tuple, or string, you can use the random.choice()
function. It randomly picks one item from the sequence and returns it.
import random
colors = ['red', 'blue', 'green', 'yellow']
print(random.choice(colors)) # green
random.choices(sequence, k=n)
This function allows you to pick n
random items from a sequence, with the possibility of repeats. It’s useful for scenarios where you need multiple random selections from the same set of options.
import random
colors = ['red', 'blue', 'green', 'yellow']
print(random.choices(colors, k=3)) # ['blue', 'green', 'green']
Here, k
is optional. If you do not pass k
, it is set to 1 by default. For example, if we do not pass k
in the above example, the output will be ['blue']
.
random.sample(sequence, k=n)
To get n
different items from a list without any repetition, use random.sample(sequence, k=n)
. This method guarantees that all the items you pick will be unique.
import random
colors = ['red', 'blue', 'green', 'yellow']
print(random.sample(colors, k=2)) # ['yellow', 'red']
Here, k
is also optional, and by default, its value is 1.
random.shuffle(sequence)
To change the order of items in a list, you can use random.shuffle(sequence)
. This function randomly rearranges the items and updates the original list.
import random
colors = ['red', 'blue', 'green', 'yellow']
random.shuffle(colors)
print(colors) # ['yellow', 'green', 'red', 'blue']
random.seed(a)
Sometimes you need the same sequence of random numbers every time your program runs. By setting a seed with random.seed(a)
, you ensure that the sequence of random numbers is the same each time. It’s like starting from the same point each time.
import random
random.seed(42)
print(random.random()) # 0.6394267984578837
random.seed(42)
print(random.random()) # 0.6394267984578837 (same result)
random.gauss(mu, sigma)
If you need numbers that follow a bell curve (normal distribution), random.gauss(mu, sigma)
generates such numbers. mu
is the average, and sigma
is the spread (standard deviation). Most numbers will be close to the average (mu
), and fewer numbers will be much higher or lower than the average.
import random
print(random.gauss(0, 1)) # -0.1432
These are a few important functions of the random
module. I hope this article helps you understand what the random
module is and teaches you the different methods it provides. Thank you for reading this article. See you soon in the next one.