How to use random.randint?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 23 2025
0607

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

  1. Import the Module: First, you need to import the random module.
  2. Call random.randint(a, b): Replace a and b with the desired range values. The function will return a random integer between a and b, including both a and b.
  3. 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.

0 Comments

no data
Be the first to share your comment!