Python – Generate a Random Number – Positive or Negative

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 – 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.

Example 1: Generate Random Number in Python

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)
Run this program

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.

Example 2: Generate 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)
Run this program

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.