Usage
The random.random()
method is used to generate a random floating-point number between 0.0 (included) and 1.0 (not included).
It’s important to note that the generated random numbers are not truly random in a cryptographic sense but are pseudorandom, which means they are generated using an algorithm with deterministic behavior based on the initial seed. If you need cryptographically secure random numbers, you should use the secrets module.
Syntax
random.random()
Parameters
None. The method doesn’t accept any parameters.
Module Import
To use random.random()
, you must first import the random module.
import random
Examples
Once the module is imported, you can simply call the function to generate a random number.
import random
print(random.random()) # Possible output: 0.58297449444842
print(random.random()) # Possible output: 0.43351443489540376
print(random.random()) # Possible output: 0.8000204571334277
The random.random()
method can often be used as a building block for more specific random generation needs. For example, to get a random float number between any two values a
and b
, you could write a function like this:
import random
def random_float(a, b):
return a + (b - a) * random.random()
print(random_float(5, 15))
# Possible output: 8.493737608123952
Or to generate a random integer within a range, you can use the following function:
import random
def random_integer(a, b):
return a + int((b - a + 1) * random.random())
print(random_integer(5, 15))
# Possible output: 8
Controlling Random Number Generation with a Seed
The random.random()
method generates pseudo-random floating-point numbers. While they seem random, these numbers are produced by a deterministic algorithm that starts with an initial value called a “seed.” This means if you use the same seed, the sequence of generated “random” numbers will be identical each time.
Let’s see how you can control this randomness by setting a seed using the random.seed() method:
import random
# Set seed for repeatability
random.seed(100)
# Print 5 random numbers between 0 and 1
for _ in range(5):
print(random.random())
# Possible output:
# 0.1456692551041303
# 0.45492700451402135
# 0.7707838056590222
# 0.705513226934028
# 0.7319589730332557
If you run this block of code again, you will get the same result.
Setting consistent seeds guarantees predictable results, which is advantageous when debugging or when you want reproducible results.