Guess the number

import random

def guess_the_number():

    number_to_guess = random.randint(1, 100)

    attempts = 0

    print(“Welcome to Guess the Number!”)

    print(“I have selected a number between 1 and 100. Try to guess it!”)

    while True:

        guess = input(“Enter your guess: “)

        if not guess.isdigit():

            print(“Please enter a valid number.”)

            continue

        guess = int(guess)

        attempts += 1

        if guess < number_to_guess:

            print(“Too low! Try again.”)

        elif guess > number_to_guess:

            print(“Too high! Try again.”)

        else:

            print(f”Congratulations! You guessed the number {number_to_guess} in {attempts} attempts!”)

            break

if __name__ == “__main__”:

    guess_the_number()

Scroll to Top