The random.randint() function is used to generate a random integer within a specified range, inclusive of both endpoints. Here’s how to use it:
Syntax
random.randint(a, b)
a: The lower bound of the range (inclusive).b: The upper bound of the range (inclusive).
Example Usage
Here’s a simple example demonstrating how to use random.randint():
import random
# Generate a random integer between 1 and 10
random_number = random.randint(1, 10)
print(f"The random number generated is: {random_number}")
Explanation
- Import the Module: First, you need to import the
randommodule. - Call
random.randint(a, b): Replaceaandbwith the desired range values. The function will return a random integer betweenaandb, including bothaandb. - Print the Result: You can print or use the generated random number as needed.
Example in a Game
Here’s how you might use random.randint() in a simple guessing game:
import random
number = random.randint(1, 10) # Random number between 1 and 10
guess = 0
while guess != number:
guess = int(input("Guess a number between 1 and 10: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
print(f"Congratulations! You guessed the number {number}!")
In this example, the player has to guess a randomly generated number between 1 and 10. The game provides feedback on whether the guess is too low or too high until the correct number is guessed.
