ExampleEdit & Run

Use the random.random() function

#import the module
import random

#Get a random value between 0.0 and 1.0
random_value = random.random()

print(random_value)
copy
Output:
0.510939568106299 [Finished in 0.012534622102975845s]

The random() function in the random module simply gets a random floating point value between 0.0 and 1.0. 

Syntax:
random()
copy

The function does not take any argument.

ExampleEdit & Run
import random

print(random.random())
copy
Output:
0.2083233035160864 [Finished in 0.012252199463546276s]

Scaling up the returned value

Whenever we want a larger number, we can scale up the value returned by the random() function by multiplying it with a larger number, like 10. For example if we want a random number between 0 and 10 we can simply multiply the value with 10 then cast it to an integer.

ExampleEdit & Run

use the random() function to get a larger integer

#import the module
import random

random_value = random.random()
print('before: ', random_value)

#Scale the value up
print('after: ', int(random_value * 10))
Output:
before:  0.7052527968608114 after:  7 [Finished in 0.011626842431724072s]
ExampleEdit & Run

Get a random value between 0 and 100

#import the module
import random

random_value = random.random()
print('before: ', random_value)

#Scale the value up
print('after: ' , int(random_value * 100))
Output:
before:  0.5882088554075563 after:  58 [Finished in 0.012105345726013184s]
ExampleEdit & Run

get a random value between 0 and 1000

#import the module
import random

random_value = random.random()
print('before: ', random_value)

#Scale the value up
print('after: ', int(random_value * 1000))
Output:
before:  0.39597006240848753 after:  395 [Finished in 0.012021506205201149s]

Get a list of random values

We can use this method to create a list containing random values.

ExampleEdit & Run

Get a list of random values

#import the module
import random

random_values = [0] * 10

for i in range(10):
   random_values[i] = random.random()

print(random_values)
Output:
[0.9607816746396596, 0.4618866949747936, 0.2961854110992438, 0.24754922230215382, 0.48094067669355756, 0.06281280089711516, 0.9199377102183359, 0.6096480600882339, 0.5678841006137809, 0.8168562597358107] [Finished in 0.012093842960894108s]
ExampleEdit & Run

Get a list of random integers between 0 and 100

#import the module
import random

random_values = [0] * 10

for i in range(10):
   random_values[i] = random.random()

random_ints = [ i for i in  map(lambda x: int(x * 100), random_values) ]

print(random_ints)
Output:
[52, 90, 80, 47, 65, 55, 31, 56, 37, 93] [Finished in 0.012647016905248165s]

In the above example, the for loop iterates through the list and assigns each value to a random number generated by the random.random() function. We then use  the map and lambda functions to multiply each random number by 100 and convert it to an integer. The result is a list of 10 random integers ranging from 0 to 100.