Generate a Random number in Python

Python provides different functions to generate random numbers, defined in random Standard library.

  • The randint() function:
    • Syntax: random.randint(x, y)
    • It return a random integer between specified range [x, y], inclusive of both x and y; i.e x <= n <= y. Here n is the number returned by randint(x, y) function.
  • The random() function:
    • Syntax: random.random()
    • The random() function doesn’t accept any arguments.
    • It return a random floating point value between [0.0, 1.0) range.

In this article we’ll see how to how to generate random number in Python programming language. Let us understand also with an example.

Example for generating integer number with randint() function

Passing the variable as an argument, and then comparing the result to the int class.

import random

print(random.randint(1, 100))
# 24

Example for generating floating point number with random() function

import random

print(random.random())
# 0.7021509552090657

Note that we may get different output because this program generates random number.

Hope you like this!

Keep helping and happy 😄 coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳