Here’s a simple Python program for the Guess the Number Game:
import random
def guess_the_number():
print("Welcome to the Guess the Number Game!")
print("I'm thinking of a number between 1 and 100.")
print("Can you guess what it is?")
# Generate a random number between 1 and 100
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
try:
# Ask the user for their guess
guess = int(input("Enter your 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 it in {attempts} attempts!")
break
except ValueError:
print("Invalid input. Please enter a valid number.")
# Run the game
guess_the_number()
How it works:
- The program generates a random number between 1 and 100.
- The user is prompted to guess the number.
- The program provides feedback:
- If the guess is too low or too high.
- If the guess is correct, it congratulates the user and ends the game.
- It keeps track of the number of attempts.
Let me know if you’d like me to modify or enhance it! 😊