Python Program to Generate a Random Number

python-program-to-generate-a-random-number

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

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:

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

Share Your Thoughts, Queries and Suggestions!