Python Program to Generate a Random number

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

  1. Start
  2. Import the “random” module: This module provides functions to generate random numbers.
  3. Take input: Prompt the user to enter the lower bound of the range.
  4. Take input: Prompt the user to enter the upper bound of the range.
  5. Generate a random number: Use the random.randint() function to generate a random number within the given range.
  6. Display the result: Print the generated random number.
  7. 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

  1. Importing the “random” module:
    The random module is part of Python's standard library, and it provides various functions for generating random numbers. Here, we are using the randint() function.
  2. Taking input from the user:
    The input() function prompts the user to enter the lower and upper bounds of the range. These inputs are converted to integers using int() since the randint() function requires integer arguments.
  3. Generating the random number:
    The random.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 variable random_number.
  4. Displaying the output:
    The print() 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.

Python

5262

606

Related Articles