Python random number between 0 and 1: Complete Guide
Python has a random module that provides different functions to generate or manipulate random numbers. The random number generator functions are used in real-time applications like lotteries, lucky draws, or games.
Python Random Number Between 0 and 1
To get a random number between 0 and 1 in Python, use the random.uniform() method. The random.uniform() method accepts two numbers and returns the random floating number between them.
Syntax
random.uniform(x, y)
Arguments
x: It is a required parameter. It is a number specifying the lowest possible outcome.
y: It is a required parameter. It is a number identifying the highest possible outcome.
Example
Use the random.uniform() method to get the floating random number between 0 and 1.
import random print(random.uniform(0, 1))
Output
0.19400286710553283
As you can see that the output floating number is between 0 and 1. It returns a random floating-point number N such that x <= N <= y for x <= y and y <= N <= x for y < x.
To generate a random float with N digits to the right of the point, use the round() function and pass the second argument of the round() function as several decimals.
import random print(round(random.uniform(0, 1), 2))
Output
0.77
We got the output with 2 decimal points because we passed 2 as a second argument to the round() function.
Generate numbers between 0 and 1 using random.random()
The Random random() method generates the number between 0.0 and 1.0. The random.random() method does not accept any parameter.
Syntax
random.random()
Arguments
The random() method does not accept any argument.
Example
Generate a random floating number using random.random() method.
import random print(random.random())
Output
0.7167279190081859
Every time you rerun the code, it will return a different output.
import random print(random.random())
Output
0.462870643862876
But you can see that it always returns the random floating number between 0 and 1.
Generate a range between 0 and 1
To generate a range of 10 numbers between 0 and 1, you can use the for loop and range() method.
import random for i in range(10): print(random.random())
Output
0.37193858005932523 0.5951347699073494 0.751762108984189 0.34839832842976537 0.6955311460839113 0.5327516816125327 0.6193354493744598 0.6677134225025977 0.7075320672349881 0.12548018574953634
Python random.randrange() Method
The randrange() is a built-in Python method that returns a randomly selected element from the specified range. Here, we can pass the range from 0 to 1. But it will not return the floating value. So it will return 0 every time you run the function.
import random print(random.randrange(0, 1))
Output
python3 app.py 0 python3 app.py 0 python3 app.py 0 python3 app.py 0
You can see from the output that it always returns 0.
That is it for this tutorial.