Robert Johns | 10 Feb, 2025
Fact checked by Jim Markus

Python random() Function | Docs With Examples

The Python random() function is your go-to tool for generating random numbers in any Python program.

That’s why it’s widely used in simulations, games, and anywhere randomness is required in Python. With Python’s random module, you can generate random float numbers, random integers, and much more, all with ease.

Importing the random Module

First things first, in order to actually use the random() function or any other function from Python’s random module, you need to import it. Thankfully, the module is included in the Python standard library:

import random

Basic Usage

In the simplest case, the Python random() function generates a pseudo-random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). This makes it ideal for pseudo-random number generators.

import random

print(random.random())

Output:

0.6783928384  # Example output (varies each time you run it)

How to Generate Random Numbers in Python

Python’s random module provides a variety of methods for generating random numbers. Here are the most common use cases:

1. Generating a Random Float in a Custom Range

To generate a random float number within a specific range, scale the result of random() to fit your desired range:

import random

# Generate a random float between 5 and 10
random_float = 5 + (random.random() * (10 - 5))
print(random_float)

2. Generating Random Integers

If you want to generate whole (integer) numbers, use we need to use randint() or randrange() instead:

# Generate a random integer between 1 and 10 (inclusive)
random_int = random.randint(1, 10)
print(random_int)

How to generate random numbers from 1 to 10 in Python?
The randint() function makes it straightforward to generate random numbers in this range.

3. Randomly Selecting from a List

If you want to pick a random element from a list, we'd need to use choice():

options = ['apple', 'banana', 'cherry']
random_choice = random.choice(options)
print(random_choice)

4. Shuffling a List

If we wanted to randomly rearrange elements in a list, we can use shuffle():

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)

Seeding the Random Number Generator

For reproducible results, use the seed() function. This ensures the same sequence of random numbers is produced every time you run the code with the same seed value. This is especially useful in testing and debugging scenarios.

random.seed(42)
print(random.random())
print(random.random())

Output:

0.6394267984578837
0.025010755222666936

Even if you run the code on a different machine, using the same seed will produce identical outputs. However, if you don't set a seed, Python will use the system time or another source of entropy to initialize the generator, resulting in different outputs each time.

When to use seeding:

- Testing and Debugging: Reproduce specific random behaviors.

- Simulations: Ensure consistent scenarios during multiple runs.

Generating Numbers from Common Distributions

Python’s random module also includes functions for generating numbers from specific statistical distributions. These functions allow you to model various real-world scenarios more accurately. Here are some common distributions you can use:

Weibull Distribution

The weibullvariate(alpha, beta) function generates numbers from a Weibull distribution:

# Generate a number from a Weibull distribution with shape parameters alpha and beta
weibull_number = random.weibullvariate(1.5, 1.0)
print(weibull_number)

Pareto Distribution

The paretovariate(alpha) function generates numbers from a Pareto distribution:

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)

Gamma Distribution

The gammavariate(alpha, beta) function generates numbers from a Gamma distribution:

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)

Exponential Distribution

The expovariate(lambd) function generates numbers from an exponential distribution:

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)

Normal Distribution

The normalvariate(mu, sigma) function generates numbers from a normal (Gaussian) distribution:

deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)

These distribution functions are invaluable when you need to simulate natural phenomena, financial models, or any scenario where randomness follows specific patterns.

Key Takeaways

- The random() function generates random floats between 0.0 and 1.0.

- We can use scaling techniques to create custom ranges for our Python projects.

- We can explore other random module functions like randint(), choice(), and shuffle() for more specific needs.

- Use statistical distribution functions for modeling more complex randomness.

- It's important to seed the generator for consistent results during testing.

Practice Exercise

Here's an interesting problem, why not try writing a program that simulates rolling dice rolls for a 6-sided die. Let's try to simulate rolling 10 times and printing the results. Hint, you might want to use the Python range function:

import random

for _ in range(10):
    print(random.randint(1, 6))

Wrapping Up

The Python random module offers powerful tools for introducing randomness into your programs. Whether you’re generating a random float number for simulations or a random integer for games, the module has you covered. By mastering these functions, you’ll be equipped to handle tasks ranging from simple simulations to complex algorithms. Remember, random numbers in Python are pseudo-random, meaning they are deterministic but appear random.

Happy coding!

 

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments