import random
def number_guessing_game():
"""A classic number guessing game."""
number = random.randint(1, 100)
guesses_left = 7
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
while guesses_left > 0:
print(f"You have {guesses_left} guesses left.")
try:
guess = int(input("Enter your guess: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print(f"Congratulations! You guessed the number {number} in {7 - guesses_left} tries!")
return
guesses_left -= 1
print(f"You ran out of guesses. The number was {number}.")
if __name__ == "__main__":
number_guessing_game()
Explanation:
Import random: This line imports the random module, which is needed to generate a random number.
number_guessing_game() function:
Initialization:
number = random.randint(1, 100): Generates a random integer between 1 and 100 (inclusive) and stores it in the number variable.
guesses_left = 7: Sets the initial number of guesses to 7.
Welcome message: Prints a welcome message and explains the game.
Game loop (while guesses_left > 0):
Print guesses remaining: Tells the player how many guesses they have left.
Get player input:
guess = int(input("Enter your guess: ")): Prompts the player to enter a guess and converts it to an integer.
Error handling: Uses a try-except block to handle cases where the player enters something that's not a number.
Check the guess:
if guess < number:: If the guess is too low, print "Too low!".
elif guess > number:: If the guess is too high, print "Too high!".
else:: If the guess is correct:
Print a congratulatory message with the number of tries.
return: Ends the function, as the game is over.
Decrement guesses:guesses_left -= 1 reduces the number of guesses remaining.
Game over: If the loop completes without a correct guess, print a message revealing the number.
if __name__ == "__main__":: This ensures that the number_guessing_game() function is only called when the script is run directly (not imported as a module).
To make it more interesting for teenagers, you could:
Add difficulty levels: Allow the player to choose a range for the random number (e.g., 1-50, 1-1000).
Keep track of high scores: Store the best scores in a file and display them.
Implement a hint system: Give the player a hint after a certain number of incorrect guesses (e.g., "The number is even").
Create a graphical user interface (GUI): Use a library like Tkinter or Pygame to make the game more visually appealing.