Introduction
Generating random numbers is a common requirement in many programming tasks, such as simulations, games, and security applications. This tutorial will guide you through creating a Python program that generates a random number within a specified range.
Problem Statement
Create a Python program that:
- Generates a random number within a specified range.
- Displays the generated random number.
Example:
- Input:
lower_bound = 1,upper_bound = 100 - Output:
Generated random number: 42
Solution Steps
- Import the
randomModule: Use Python’s built-inrandommodule to generate random numbers. - Specify the Range: Define the lower and upper bounds for the random number generation.
- Generate the Random Number: Use the
random.randint()function to generate a random number within the specified range. - Display the Result: Use the
print()function to display the generated random number.
Python Program
# Python Program to Generate a Random Number
# Author: https://www.rameshfadatare.com/
import random
# Step 1: Specify the range for the random number
lower_bound = int(input("Enter the lower bound: "))
upper_bound = int(input("Enter the upper bound: "))
# Step 2: Generate the random number within the specified range
random_number = random.randint(lower_bound, upper_bound)
# Step 3: Display the result
print(f"Generated random number: {random_number}")
Explanation
Step 1: Specify the Range for the Random Number
- The user is prompted to enter the lower and upper bounds for the random number generation. These inputs are converted to integers using
int().
Step 2: Generate the Random Number
- The
random.randint()function from Python’srandommodule is used to generate a random integer within the specified range, inclusive of both bounds.
Step 3: Display the Result
- The
print()function is used to display the generated random number. Thef-stringformat is used to include the random number directly within the output string.
Output Example
Example:
Enter the lower bound: 1
Enter the upper bound: 100
Generated random number: 42
Example:
Enter the lower bound: 10
Enter the upper bound: 50
Generated random number: 37
Conclusion
This Python program demonstrates how to generate a random number within a specified range using Python’s random module. It’s a practical example for beginners to understand random number generation and user input handling in Python.