Skip to main content

How to generate a random number in Python

How to generate a random number in Python.

Here's a step-by-step tutorial on how to generate a random number in Python:

Step 1: Import the random module

To generate random numbers in Python, you need to import the random module. You can do this by adding the following line of code at the beginning of your script:

import random

Step 2: Use the random() function

The random module provides several functions for generating random numbers. One of the simplest ways to generate a random number is by using the random() function. This function returns a random float number between 0 and 1 (inclusive of 0, but not 1). Here's an example:

import random

num = random.random()
print(num)

This will output a random float number such as 0.634568293.

Step 3: Generate random integers

If you want to generate random integers instead of floats, you can use the randint() function. This function takes two arguments: the lower bound and the upper bound of the range from which the random number will be selected. The upper bound is not inclusive. Here's an example:

import random

num = random.randint(1, 10)
print(num)

This will output a random integer between 1 and 10, including both 1 and 10.

Step 4: Generate random numbers within a specific range

If you want to generate random numbers within a specific range, you can use the uniform() function. This function takes two arguments: the lower bound and the upper bound of the range. It returns a random float number within the specified range. Here's an example:

import random

num = random.uniform(2.5, 5.5)
print(num)

This will output a random float number between 2.5 and 5.5.

Step 5: Generate random numbers from a list or sequence

You can also generate random numbers from a list or sequence of values using the choice() function. This function takes a list as an argument and returns a random element from that list. Here's an example:

import random

numbers = [1, 2, 3, 4, 5]
num = random.choice(numbers)
print(num)

This will output a random element from the numbers list, such as 3.

Step 6: Generate random numbers with a specific distribution

If you need random numbers with a specific distribution, such as a Gaussian (normal) distribution, you can use the functions provided by the random module. For example, the gauss() function generates random numbers following a Gaussian distribution. Here's an example:

import random

num = random.gauss(0, 1)
print(num)

This will output a random float number following a Gaussian distribution with a mean of 0 and standard deviation of 1.

That's it! You now know how to generate random numbers in Python using the random module. Feel free to explore other functions and methods provided by the random module for more advanced random number generation.