Python’s Random Module: A Comprehensive Guide
The random
module is essential for data science, data engineering, and machine learning. It’s also popular in game development and widely used in software design. This in-built Python function is straightforward to use once you understand when and how to apply it.
In this article, we discuss the random
module and its various uses.
Generating Random Numbers
The random
function generates computer-chosen random numbers based on user specifications. You can select a specific set or range of numbers, and the computer produces numbers based on your commands. To start, import the random
module:
Key Functions of the Random
Module
- Generate a Random Integer (
randint
)
import random
a = random.randint(1, 7)
print(a)
# Output could be any number from 1 to 7
Here, random.randint
sets the range from 1 to 7, and any number within this range can be generated.
2. Generate a Random Integer (Using randrange
)
Another function, randrange
, also generates numbers but excludes the upper limit:
a = random.randrange(1, 7)
print(a)
# Output will be any number from 1 to 6
3. Generate a Random Float (random
)
The random.random()
function produces a float between 0 and 1:
a = random.random()
print(a)
# Output: a float between 0 and 1
4. Generate a Float Within a Range (uniform
)
To generate a float within a specified range, use random.uniform
:
a = random.uniform(1, 3)
print(a)
# Output: a float between 1 and 3
5. Select a Random Item from a List (choice
)
If you have a list, you can select a random element:
l = [2, 5, 9, -5, 89, 12, 56]
a = random.choice(l)
print(a)
# Output: any number from list `l`
6. Shuffle List Elements (shuffle
)
To shuffle a list, use random.shuffle
:
l = [2, 5, 9, -5, 89, 12, 56]
random.shuffle(l)
print(l)
# Output: a rearranged version of `l`
Real-World Example: Rock-Paper-Scissors Game
Suppose,
Rock wins against Scissor
Scissor win against paper
Paper wins against rock
0 for rock
1 for paper
2 for scissor
USER | COMPUTER | RESULT |
---|---|---|
Input | Input | Output |
0 | 0 | Draw |
0 | 1 | Computer win |
0 | 2 | User win |
1 | 0 | User win |
1 | 1 | Draw |
1 | 2 | Computer win |
2 | 0 | Computer win |
2 | 1 | User win |
2 | 2 | Draw |
The random
module can be used to make games. Here’s an example of a simple Rock-Paper-Scissors game:
import random
user = int(input("Enter a number (0 for rock, 1 for paper, 2 for scissors): "))
if user < 0 or user > 2:
print("You entered an invalid number.")
else:
computer = random.randint(0, 2)
print(f"Computer chose: {computer}")
if user == computer:
print("The game is a draw")
elif (user == 0 and computer == 2) or (user == 2 and computer == 1) or (user == 1 and computer == 0):
print("User wins!")
else:
print("Computer wins!")
In this code, the computer generates a random choice between 0 and 2, representing rock, paper, and scissors, and the program compares it with the user’s input.