Number Guessing game in Python Code

To play the game, run the script in a Python environment, and follow the prompts to enter your guesses. The program will provide feedback until you guess the correct number.

Code

import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Set the initial number of guesses
num_guesses = 0

print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")

while True:
    # Get user's guess
    guess = int(input("Take a guess: "))

    # Increment the number of guesses
    num_guesses += 1

    # Compare the guess with the secret number
    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print(f"Congratulations! You guessed the number in {num_guesses} attempts.")
        break

Output

In this game, the computer generates a random number between 1 and 100 using the function. The player’s goal is to guess the number correctly. After each guess, the program provides feedback by indicating if the guess is too low or too high. If the guess matches the secret number, the game ends, and the program displays the number of attempts made by the player.

Note:- Feel free to customize the game by adjusting the range of the secret number or adding additional features such as difficulty levels or score tracking.