For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
How does Python help you build games, simulations, or lucky draws with just one line?
It all starts with the random function in Python.
The random module in Python lets you generate random numbers, shuffle items, pick random elements, and create unpredictability in your programs. Whether you're simulating dice rolls, shuffling a deck, or splitting datasets, the random function in Python makes it easy.
In this guide, you’ll explore how to use popular functions like random(), randint(), choice(), and shuffle() from the random module. You’ll also learn when and why to use each function, with simple examples to help you practice and apply them right away.
By the end, you’ll be ready to build Python programs that behave differently every time they run. Want to use randomness in real-world data projects? Check out our Data Science Courses and Machine Learning Courses for practical applications of Python’s random features.
The random module in Python allows you to generate random numbers and make your programs more dynamic.
To use the random function, you first need to import the random module.
Once that’s done, you can use various functions within the module, such as random.randint(), to generate random numbers.
Let’s break it down with an example.
# Importing the random module
import random
# Using random.randint in python to generate a random integer between 1 and 10
random_number = random.randint(1, 10) # This will generate a random number between 1 and 10 (inclusive)
# Output the result
print(f"Random number generated: {random_number}")
Output:
Random number generated: 7
Explanation:
Now, you’ve successfully generated a random integer between two values. You can modify the numbers to fit your needs.
Looking to bridge the gap between Python practice and actual ML applications? A formal Data Science and Machine Learning course can help you apply these skills to real datasets and industry workflows.
The Python random module offers a variety of functions to generate random numbers, shuffle data, and sample values from sequences.
Below is a list of some key functions within the random module:
Function Name | Description |
random.random() | Returns a random floating-point number in the range [0.0, 1.0). |
random.randint(a, b) | Returns a random integer N such that a <= N <= b. |
random.uniform(a, b) | Returns a random floating-point number N such that a <= N <= b. |
random.choice(sequence) | Returns a randomly selected element from a non-empty sequence (e.g., list, tuple, etc.). |
random.choices(population, k) | Returns a list of k random elements from the population with replacement. |
random.sample(population, k) | Returns a list of k unique random elements from the population without replacement. |
random.shuffle(sequence) | Shuffles the sequence in place, meaning the elements are randomly reordered. |
random.seed(a=None) | Initializes the random number generator to a specific state to produce reproducible results. |
random.triangular(low, high, mode) | Returns a random floating-point number in the range [low, high] with a triangular distribution. |
random.betavariate(alpha, beta) | Returns a random float from the Beta distribution. |
random.expovariate(lambd) | Returns a random float from the exponential distribution. |
random.gammavariate(alpha, beta) | Returns a random float from the Gamma distribution. |
random.gauss(mu, sigma) | Returns a random float from the Gaussian distribution (normal distribution). |
random.lognormvariate(mu, sigma) | Returns a random float from the log-normal distribution. |
random.vonmisesvariate(mu, kappa) | Returns a random float from the von Mises distribution. |
random.paretovariate(alpha) | Returns a random float from the Pareto distribution. |
random.weibullvariate(alpha, beta) | Returns a random float from the Weibull distribution. |
These functions provide flexibility and a variety of randomization tools to enhance your Python programs.
These examples will help you understand how to call random functions in Python and apply them effectively in real-world applications.
You can use the random.choice() function to select a random value from a list. This is useful when you want to randomly pick an item from a list without having to index it manually.
import random
# List of colors
colors = ['Red', 'Blue', 'Green', 'Yellow', 'Purple']
# Select a random color
random_color = random.choice(colors)
# Print the selected random color
print("Random color:", random_color)
Output:
Random color: Green
Explanation:
You can use random.seed() to initialize the random number generator to a specific state, ensuring that you get the same sequence of random numbers each time you run your code. This is helpful for debugging or testing.
import random
# Set the seed for reproducibility
random.seed(10)
# Generate a random number
random_number = random.randint(1, 100)
# Print the random number
print("Random number with seed:", random_number)
Output:
Random number with seed: 74
Explanation:
You can generate random numbers using random.randint(). This function returns a random integer between two specified values (inclusive).
import random
# Generate a random integer between 1 and 10
random_int = random.randint(1, 10)
# Print the random integer
print("Random integer:", random_int)
Output:
Random integer: 6
Explanation:
If you want to generate random floating-point numbers, you can use random.uniform(), which returns a random float between two specified values.
import random
# Generate a random float between 1.5 and 10.5
random_float = random.uniform(1.5, 10.5)
# Print the random float
print("Random float:", random_float)
Output:
Random float: 7.9234125342637
Explanation:
If you want to shuffle the elements of a list randomly, you can use the random.shuffle() function. This method shuffles the list in place, meaning it modifies the original list.
import random
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Shuffle the list
random.shuffle(numbers)
# Print the shuffled list
print("Shuffled list:", numbers)
Output:
Shuffled list: [3, 5, 1, 4, 2]
Explanation:
These methods are useful in many scenarios, such as selecting random items and generating random numbers. Keep experimenting with these functions to understand their behavior and applications better!
In this section, we will create a simple Rock-Paper-Scissors game using the Python random module. This is a great way to apply what you've learned about random functions and see how they can be used to simulate a game.
Step 1: Importing the Random Module
First, we need to import the random module, which will allow us to generate random choices for the computer.
import random
Step 2: Defining the Game Choices
Next, we define the available choices for the game: Rock, Paper, and Scissors.
choices = ['rock', 'paper', 'scissors']
Step 3: Taking the User’s Input
Now, we'll prompt the user to input their choice. To ensure the input is valid, we’ll also convert it to lowercase.
user_choice = input("Enter rock, paper, or scissors: ").lower()
Step 4: Randomly Generating the Computer’s Choice
Now, we use the random.choice() function to randomly select one of the three choices for the computer.
computer_choice = random.choice(choices)
Step 5: Displaying the Choices
We then print both the user's and the computer's choices.
print(f"You chose: {user_choice}")
print(f"The computer chose: {computer_choice}")
Step 6: Determining the Winner
Now, we will compare the user’s choice with the computer’s choice and determine the winner. The rules of the game are:
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'scissors' and computer_choice == 'paper') or \
(user_choice == 'paper' and computer_choice == 'rock'):
print("You win!")
else:
print("You lose!")
Step 7: Running the Program
Here’s the complete code for the Rock-Paper-Scissors game:
import random
choices = ['rock', 'paper', 'scissors']
# Taking user's input
user_choice = input("Enter rock, paper, or scissors: ").lower()
# Generating computer's choice
computer_choice = random.choice(choices)
# Displaying choices
print(f"You chose: {user_choice}")
print(f"The computer chose: {computer_choice}")
# Determining the winner
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'scissors' and computer_choice == 'paper') or \
(user_choice == 'paper' and computer_choice == 'rock'):
print("You win!")
else:
print("You lose!")
Sample Output:
Enter rock, paper, or scissors: rock
You chose: rock
The computer chose: scissors
You win!
Explanation:
By understanding how to call random function in Python and handling inputs, you can create more complex games and applications in the future.
1. Which module in Python provides functions for random number generation?
a) math
b) random
c) numpy
d) randomize
2. What does random.random() return?
a) A random integer
b) A float between 0 and 1
c) A string
d) A boolean
3. What is the output type of random.randint(1, 5)?
a) Any float between 1 and 5
b) Integer between 1 and 5 (inclusive)
c) Only 1 or 5
d) Error if 1 > 5
4. What does the function random.choice(['a', 'b', 'c']) return?
a) The entire list
b) A random character from the list
c) A sorted list
d) Error
5. Which function will randomly shuffle elements of a list in place?
a) random.shuffle(list)
b) random.sort(list)
c) list.random()
d) shuffle.random(list)
6. What will random.randrange(10, 20, 2) return?
a) Any even number from 10 to 20 (excluding 20)
b) A float
c) A number from 1 to 10
d) Error
7. What is the difference between random.random() and random.uniform(1, 5)?
a) Both return the same range
b) random.random() returns 0 to 1, uniform() returns custom float range
c) uniform() only works on integers
d) random() is deprecated
8. Which function helps select multiple unique random elements from a list?
a) random.select()
b) random.sample()
c) random.shuffle()
d) random.pick()
9. You need to simulate rolling a dice. Which line is best?
a) random.randint(1, 6)
b) random.random()
c) random.choice(6)
d) random.uniform(1, 6)
10. A student uses random.seed(5) before calling random.random() multiple times. What is the purpose?
a) To generate faster results
b) To get the same sequence every time (reproducibility)
c) To disable randomness
d) It has no effect
11. You want to randomly select 3 students from a list of 10 without repeating any. Which method should you use?
a) random.choices(list, k=3)
b) random.choice(list)
c) random.sample(list, 3)
d) list.shuffle()
The random.randint function in Python is used to generate a random integer between two specified numbers, inclusive. It’s commonly used in games or simulations where you need a random integer.
To call random function in Python, you can use functions like random.randint or random.random(). random.randint() allows you to specify a range of integers to choose from.
Yes, random.randint in Python can be used in games like Rock-Paper-Scissors to generate random choices for the computer, providing a dynamic experience for the user.
To shuffle a list in Python, use the random.shuffle() function. This modifies the list in place and randomly arranges the elements in it.
The random.randint() function returns a random integer within the range you specify, including both endpoints. It’s perfect for cases where you need random selection from a specific range.
To generate a random float in Python, use random.random() or random.uniform(). The former returns a float between 0 and 1, and the latter allows you to specify a range.
Yes, random.randint in Python can generate negative numbers if you specify a negative range, like random.randint(-10, -1) to get random values between -10 and -1.
To select a random element from a list, you can use random.choice() in Python. This function randomly picks one element from the list.
random.randint in Python is ideal for making random decisions in scenarios like games or simulations, where you need to choose between multiple options, such as picking a number between 1 and 6 for a dice roll.
To generate a random float in a specific range, you can use random.uniform(a, b) in Python, where a and b define the range.
While random.randint() can’t directly select a character, you can use it to pick a random index and then retrieve the character from that index in the string.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.