Python Program to Generate a Random Number

Python program to generate a random number. There are two Python language program to produce random number. In the first program there is no range or limit. However, in second program, random variable generated with in given range. This program is useful for beginners, CBSE class 11, 12 and B Tech Computer science with python lab and board exams.

Program 1: Python Program to Generate a Random Number

In Python programming, we can generate a random integer, doubles, longs in various ranges by importing a “random” class.
In the following example, we will learn how to generate random numbers using the random module.

Source code:

import random  
n = random.random()  
print(n)

Click below button to Download Source Code

Source code explanation

  • Random library is imported.
  • Random function of Random library is called and assigned to a variable n
  • The variable n is printed

Output of Program:

Output Explanination

It gives the random variable without any limiting to the value.

Program 2 : Generating a Random variable in a given Range

Python random module provides the randint() method that generates an integer number within a specific range. We can pass the two numbers as arguments that defines the range. Let’s understand the following example.

Source code :

import random  
n = random.randint(0, 50)  
print(n)
  • Random library is imported.
  • Random function of Random library is called and assigned to a variable n
  • The function randint(0,50) is giving what is in between in the range.
  • The variable n is printed

Output:

Output Explaination:

The number is between 0 and 50 as assigned by randint(0,50)

Thank you for reading and learning Program to Generate a Random number within a range or not in range . Both of the program have been mentioned with source code and output is also shown. This program is useful for CBSE class 11, 12 and B Tech Computer science with python lab and board exams. Below are the links for more programs.

Python Programs Archives – CS Study

Computer Science Practical file for class 12 Term-2 – CS Study

Computer Science with Python Practical Book Solutions Class 11 Term -2 – CS Study

Leave a Comment

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

Exit mobile version