Write a Python program that generates a random number within a specified range provided by the user.
Input-Output Examples
plaintext
Example 1:
Input:
Enter the lower bound: 1
Enter the upper bound: 10
Output:
Random number between 1 and 10: 7 (Note: The actual number may vary as it is generated randomly.)
Example 2:
Input:
Enter the lower bound: 50
Enter the upper bound: 100
Output:
Random number between 50 and 100: 85 (Note: The actual number may vary.)
Algorithm to generate random number in Python
- Start
- Import the “random” module: This module provides functions to generate random numbers.
- Take input: Prompt the user to enter the lower bound of the range.
- Take input: Prompt the user to enter the upper bound of the range.
- Generate a random number: Use the
random.randint()
function to generate a random number within the given range. - Display the result: Print the generated random number.
- End
Python Program to generate Random numbers
python
# Python program to generate a random number within a specified range
# Import the random module to use its functions
import random
# Take input from the user for the lower and upper bounds of the range
lower_bound = int(input("Enter the lower bound: "))
upper_bound = int(input("Enter the upper bound: "))
# Generate a random number between the lower and upper bounds (inclusive)
random_number = random.randint(lower_bound, upper_bound)
# Display the generated random number
print(f"Random number between {lower_bound} and {upper_bound}: {random_number}")
Code Explanation
- Importing the “random” module:
Therandom
module is part of Python's standard library, and it provides various functions for generating random numbers. Here, we are using therandint()
function. - Taking input from the user:
Theinput()
function prompts the user to enter the lower and upper bounds of the range. These inputs are converted to integers usingint()
since therandint()
function requires integer arguments. - Generating the random number:
Therandom.randint(lower_bound, upper_bound)
function generates a random integer between the lower bound and upper bound (both inclusive). The result is stored in the variablerandom_number
. - Displaying the output:
Theprint()
function displays the generated random number along with the range provided by the user. An f-string is used to format the output for clarity.