View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Random Function in Python: Uses, Syntax, and Examples

Updated on 02/06/20258,913 Views

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.

How to Use the Random Function in Python

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:

  • import random: This imports the Python random module so that we can use its functions.
  • random.randint(1, 10): This generates a random integer between the numbers 1 and 10 (both inclusive).
  • print(f"Random number generated: {random_number}"): This prints the generated random number.

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.

List of All the Functions of the Python Random Module

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.

Random in Python Examples

These examples will help you understand how to call random functions in Python and apply them effectively in real-world applications.

Printing a Random Value from a List in Python

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:

  • random.choice(colors) randomly selects one element from the colors list.
  • The output will be different each time the program is run.

Creating Random Numbers with Python seed()

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:

  • random.seed(10) ensures that the random numbers generated will be the same on each run.
  • Using random.randint(1, 100), you get a random integer between 1 and 100.

Generate Random Numbers in Python

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:

  • random.randint(1, 10) generates a random integer between 1 and 10.
  • Each time you run the code, you will get a different result.

Generate Random Float Numbers in Python

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:

  • random.uniform(1.5, 10.5) generates a random float between 1.5 and 10.5.
  • The value will be a floating-point number, which is different each time you run the program.

Shuffle List in Python

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:

  • random.shuffle(numbers) shuffles the elements of the numbers list randomly.
  • The order of elements in the list will be different each time you run the program.

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!

Rock-Paper-Scissors Program Using Random Module

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:

  • Rock beats Scissors
  • Scissors beats Paper
  • Paper beats Rock
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:

  • Random Choice: We used random.choice() to select the computer's choice randomly from the available options.
  • Input Handling: The user's input is taken and converted to lowercase to handle case sensitivity.
  • Conditionals: The game uses if, elif, and else to determine the outcome based on the game's rules.

By understanding how to call random function in Python and handling inputs, you can create more complex games and applications in the future.

MCQs on Random Function in Python

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()

FAQs

1. What is the purpose of using random.randint in Python?

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.

2. How to call random function in Python to get random numbers?

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.

3. Can I use random.randint in Python for a simple game?

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.

4. How to call random function in Python to shuffle a list?

To shuffle a list in Python, use the random.shuffle() function. This modifies the list in place and randomly arranges the elements in it.

5. How does random.randint() work in Python?

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.

6. How to call random function in Python for a float number?

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.

7. Can random.randint in Python generate negative numbers?

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.

8. How to call random function in Python for selecting random elements from a list?

To select a random element from a list, you can use random.choice() in Python. This function randomly picks one element from the list.

9. What is the use of random.randint in Python when making random decisions?

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.

10. How to call random function in Python for generating a random float in a range?

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.

11. Is it possible to use random.randint in Python to select a random character from a string?

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.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.