Skip to content
Home » Programming » Python Program to Generate a Random Number

Python Program to Generate a Random Number

Python Program to Generate a Random Number

In this post, we will be investigating the Python Program to Generate a Random Number. We will generate a random number and clarify the linguistic structure; simply referred to as syntax of the program.

Algorithm to Generate a Random Number

In order to generate a random number; we have to import a library package known as random and randint() function is used and is defined as a random module.

We will use two variables; a and b to specify the range of the random number; where a will be the lower limit of the range and b will be the upper limit of the range.

Let us take a look to the algorithm to generate a random number in Python.

Step 1: Start
Step 2: Import the library package 'random'
Step 3: Initialize two values; a and b
Step 4: Display the random number using randint() function i.e.
                   print(random.randint(a, b)
Step 5: End

In Python program, there is a simple way to generate a random number. The algorithm shown above can generate a random number between the specified range without performing any complex calculations (simply dragging the random number from the random module).

New to Python Programming?  Start with Python Programming!

Generating a Random Number in Python

Focusing on the Program to Generate a Random Number, let’s jump into the source code.

Example 1: Program with specified range

#importing the library package
import random

#display the random number using the randint()
print(random.randint(0, 9)

The output of the above code snippet is;

3

Note that we often get different values for different execution of the program; as this program is meant to generate random number in the range of 0 to 9.

Explanation

The basic idea behind the syntax of the function is:

random.randint(a,b)

This means that it returns a number (random) N in the inclusive range [a,b] i.e. a <= N <= b.


You may also check —>


Leave a Reply

Your email address will not be published. Required fields are marked *