How to generate a random number between 0 and 1 in Python

Use the random() method from the random module to generate a float number between 0 and 1.

0 is included as a possible outcome and 1 is excluded, meaning the method might return a 0, but never 1.

import random

random_float = random.random()

print(random_float)
0.5893102480755269

If you want to include 1 as a possible outcome, use the uniform() method.

import random

random_float = random.uniform(0, 1)

print(random_float)
0.291298534824892

Watch on Youtube

You can also watch this content on Youtube: