Build a simple number guessing game where the program randomly selects a number, and the player has to guess it. You can provide hints like “too high” or “too low.”
import random
def number_guessing_game():
print(“Welcome to the Number Guessing Game!”)
print(“I am thinking of a number between 1 and 100.”)
# Generate a random number between 1 and 100
number_to_guess = random.randint(1, 100)
attempts = 0
guessed = False
while not guessed:
guess = int(input("Make a 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 in {attempts} attempts.")
guessed = True</code></pre>
Leave a Reply