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
View All
View All
View All
View All
View All
View All
View All
View All
View All

Random Function in Python

Updated on 27/01/20258,641 Views

The random function in Python generates random values such as integers or floating-point numbers. It’s essential for tasks like simulating dice rolls or creating random datasets. However, many developers struggle to call random functions in Python efficiently.

The problem arises when you are unsure which random function to use or how to specify its behavior. Without the right syntax, generating a random integer within a certain range or picking a random element from a list can be tricky.

In this guide, you’ll learn how to call random function in Python and how to use it to generate random data effectively. We’ll focus on functions like random.randint in Python and explore practical examples. Read on!

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

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.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

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: rockYou chose: rockThe computer chose: scissorsYou 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.

FAQs

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

A. 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?

A. 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?

A. 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?

A. 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?

A. 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?

A. 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?

A. 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?

A. 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?

A. 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?

A. 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?

A. 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

+918045604032

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.