Untitled

 avatar
unknown
plain_text
a month ago
888 B
2
Indexable
import random

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

# Initialize variables
attempts = 0
guessed_correctly = False

print("Welcome to the Number Guessing Game!")
print("I have selected a number between 1 and 100. Can you guess it?")

# Game loop
while not guessed_correctly:
    try:
        # Get user input
        player_guess = int(input("Enter your guess: "))
        attempts += 1

        # Check if the guess is correct
        if player_guess < number_to_guess:
            print("Too low! Try again.")
        elif player_guess > number_to_guess:
            print("Too high! Try again.")
        else:
            guessed_correctly = True
            print(f"Congratulations! You've guessed the number in {attempts} attempts.")

    except ValueError:
        print("Please enter a valid number.")
Editor is loading...
Leave a Comment