Chrome Extension

How to generate a random number in python using random module

To generate a random number in python you can use the python module - random. It provides many functions like randint(), random(), etc to generate a random number.
import random

print (random.randint(1,50))
#It will print a random number between 1 to 50

print (random.random())
#It will print a Float random number between 0 to 1

print(random.sample( range(5, 24), 7) )
# Prints a list of 7 random numbers between 5 to 24
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

In the above code snippet we are genrating random numbers using random module. To import random module of python you can use below code.

import random

Generate a Random Integer Number using randint() method

The easiest way to generate a random number of Integer type is by using the randint() method of random. For example, if you want to generate a random number between 2 to 15, you can use the below code

import random

random_int = random.randint(2,15)
print(random_int)

The above code will print out a random number between 2 to 15 each time you run the code.

Generate a random Float number between 0 to 1

To generate a random float number between 0 to 1 you can use the random module method .random().

import random

float_num = random.random()
print(float_num)

The above code will prints a random float number each time you run the code.

Generate a List of random numbers with N items

If you want to generate a list of random numbers in python using the random module, you can use the .sample() method of the random module.

For example, to generate a list of 10 items that contain random integers, the below code can be used.

import random

random_list = random.sample( range(7, 65), 10)
print(random_list)

The above code will print a list of 10 items which will contain random integer type values between 7 to 65.

Search Index Data (The code snippet can also be found with below search text)

random module python
Was this helpful?
0 Comments