Generate a Random Number in Python - Examples


Generate Random Number in Python

Random Number is of interest in applications like signal processing, data analysis, statistics, etc. You can generate a random number in Python programming using Python module named random.

To generate a random number in python, you can import random module and use the function randInt().

In this tutorial, we shall learn how to generate a random number using Python random module.

Syntax of randInt()

You have to import random package, before you can call any functions of it in your program. Following statement imports random package to your program.

import random

The syntax of randInt() is:

randomnumber = random.randint(minimum, maximum)

where

  • [minimum, maximum] is the range from which a random integer is picked
  • randint() function returns an integer

Generating a random number has applications in simulating uniform probabilistic events, gambling, statistical sampling, etc.

Examples

1. Generate a random number

In the following example, we will generate a random number within the range [10, 152].

Python Program

import random

randomnumber = random.randint(10, 152)
print(randomnumber)

Output

C:\python>python example.py
144

C:\python>python example.py
12

C:\python>python example.py
79

C:\python>python example.py
54

Everytime randint() function is run, a different number is generated randomly.

2. Generate a random negative number

You can provide a negative range to pick a random number from. Provide the maximum and minimum with valid negative numbers.

In the following example, we will generate a random number within the range [-100, -21].

Python Program

import random

randomnumber = random.randint(-100, -21)
print(randomnumber)

Output

C:\python>python example.py
-74

C:\python>python example.py
-95

C:\python>python example.py
-70

Summary

In this tutorial of Python Examples, we learned how to generate a random number in Python with the help of well detailed examples.