Generate Random Number Using Python

May 25, 2018

1 min read

Published in

Need some random numbers in your program? This article will help you to know different techniques to generate a random number in python. While developing small, large or enterprise applications, It requires generating random numbers. Let’s deep dive to Generate Random number using Python.

Python provides a ” random ” library to generate a random number using built un methods. Just “import random” and start generating a number which will be random.

Here is the example to generate a random integer number.

Generate Random number using Python

Using randint(a,b)

1
2
3
4
# Program to print 5 random integer numbers between 1 to 10000
import random
for x in range(5):
    print random.randint(1, 10000)

This program prints 5 random integer numbers between 1 to 10000. randint is an inbuilt function in python random library. It has two parameters.randint(a,b) It generates the random integer number N such that.a <= N <= b

Using random()

1
2
3
# Program to print 5 random numbers between 0.0 to 1.0
for x in range(5):
    print random.random()

This random function returns the random floating-point number in the range (0.0, 1.0).

For more information to generate random numbers, please visit the official python document for random.

https://docs.python.org/3/library/random.html

To learn more about Python, Please visit the Python category.

 

Sharing is caring!