Python Program to Generate a Random Number

schedule
2022-07-13 | 16:28h
update
2023-01-09 | 18:06h
person
Pankaj Bhadwal
domain
TechStrot
Python Program to Generate a Random Number

In this PythonAMP example, you will learn about the Python program to generate a random number. The program will make use of the Random module.

Table of Contents

ToggleAMP

Python Program to Generate a Random Number

  • Program to Generate a Floating-Point Number Between 0 and 1

Here, we are going to discuss a simple Python program that will leverage the random() method available within the Random module to generate a random float value between 0 and 1.

Also, we will use the print() function to output the random value generated by the random() method.

Below is the code to generate a random floating-point number between 0 and 1:

Advertisement

#import the random module import random  #use random() method to generate a floating-point number between 0 and 1 n = random.random()  #output the generated value in the console print(n)

Output:

0.7113841073816167
  • Program to Generate a Random Number From a Specified Number Range

We can generate a number within a specific range by using the randint() method available within the random module as shown in the code below:

#import the random module import random #use randint() method to generate a number between 0 and 100 n = random.randint(1,100) #output the generated value in the console print(n)

Output:

10

Takeaway

Generating random numbers is an important aspect of programming, and it’s quite easy to accomplish the same. A fully dedicated online Python Course will explain the important concepts of python programming with real-time project work.

There are several instances where we need to generate a random number to meet certain objectives of the overall Python program.

For instance, there are several games that require the generation of random numbers, and we can use the random() and randint() methods to accomplish the same.

Advertisement

Imprint
Responsible for the content:
www.techstrot.com
Privacy & Terms of Use:
www.techstrot.com
Mobile website via:
WordPress AMP Plugin
Last AMPHTML update:
25.10.2025 - 14:40:14
Privacy-Data & cookie usage: