In this example, you will learn to generate a random number using Python.
Example 1: Generate a random number with a specified range.
import random
# Get the range of numbers from the user
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
# Generate a random number within the specified range
random_number = random.randint(start, end)
print(f"The random number between {start} and {end} is: {random_number}")
In this program, we start by importing the random
module, which provides functions for generating random numbers. We then ask the user to enter the start and end of the range for the random number.
We use the randint()
function from the random
module to generate a random integer between the two values provided by the user, and store it in a variable called random_number
.
Finally, we output the generated random number using an f-string.
Here’s an example of the output of the program:
Enter the start of the range: 1
Enter the end of the range: 100
The random number between 1 and 100 is: 64
Example 2: Program that simulates a dice roll
import random
# Generate a random number between 1 and 6
dice_roll = random.randint(1, 6)
print(f"You rolled a {dice_roll}")
In this program, we use the randint()
function from the random
module to simulate a dice roll. We store the generated number in a variable called dice_roll
, and output it to the user.
Example 3: A program that generates a random RGB color value:
import random
# Generate three random numbers between 0 and 255
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
# Format the RGB value as a string
rgb = f"({r}, {g}, {b})"
print(f"The random RGB value is: {rgb}")
In this program, we use the randint()
function from the random
module to generate three random integers between 0 and 255, which correspond to the red, green, and blue values of an RGB color.
We store these values in separate variables and format them as a string using an f-string. Finally, we output the generated RGB value to the user.