Python Program to Generate a Random Number

In this post, we will learn how to generate a random number using Python Programming language.

This program will use the randint() function to generate a random number between a given range.

We will perform this task using the following approaches:

1. Using Standard Method
2. Random Number in a Range

So, without further ado, letâ€™s begin this tutorial.

Python Program to Generate a Random Number

# Python Program to Generate a Random Number

# importing the random module
import random

# Generating random number
print("Generated random number is: ", random.randint(0, 25))

Output 1

Generated random number is:  8

Output 2

Generated random number is:  6

Output 3

Generated random number is:  1

How Does This Program Work ?

# importing the random module
import random

We import random module in our python program. This module contains the randint() function which is used for generating random numbers.

# Generating random number
print("Generated random number is: ", random.randint(0, 25))

The randint() function returns an integer selected element from the specified range. randint() is an inbuilt function of the random module in Python3.

This program generates and displays a random number lying between 0 and 25 (including both 0 and 25).

Python Program to Generate a Random Number in a Given Range

# Python Program to Generate a Random Number in a Given Range

# Importing the random module
import random

start = int(input("Enter the starting number: "))
last = int(input("Enter the last number: "))

# Generating random number
num = random.randint(start, last)

# Displaying output
print("Generated random number is: ", num)

Output 1

Enter the starting number: 5
Enter the last number: 25
Generated random number is:  15

Output 2

Enter the starting number: 5
Enter the last number: 25
Generated random number is:  7

Conclusion

I hope after going through this post, you understand how to generate a random number using Python Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.