556
In this game, the computer generates a random number between 1 and 100, and the player has to guess it.
After each guess, the computer will tell the player if the guess is too high, too low, or correct.
The player continues to guess until they find the correct number.
Code:
import random def higher_lower_game(): print("Welcome to the Higher-Lower Game!") print("I'm thinking of a number between 1 and 100.") # Generate a random number between 1 and 100 target_number = random.randint(1, 100) # Set the initial number of attempts attempts = 0 while True: try: # Get user's guess guess = int(input("Make a guess: ")) attempts += 1 # Increment the attempt count # Check if the guess is too high, too low, or correct if guess < target_number: print("Too low. Try again!") elif guess > target_number: print("Too high. Try again!") else: # If guess is correct, print success message and break the loop print(f"Congratulations! You guessed the number {target_number} in {attempts} attempts.") break except ValueError: # Handle cases where the user doesn't input an integer print("Please enter a valid integer.") # Run the game higher_lower_game()
Explanation of the Code
- Import the random Module:
- random is a standard Python module that provides functions for generating random numbers.
- We use random.randint() to generate a random integer within a specified range.
- Define the higher_lower_game Function:
- This function contains the entire game logic.
- Introduction to the Game:
- print(“Welcome to the Higher-Lower Game!”): Greets the player.
- print(“I’m thinking of a number between 1 and 100.”): Informs the player of the range of numbers.
- Generate a Target Number:
- target_number = random.randint(1, 100): Generates a random integer between 1 and 100, which the player will try to guess.
- This random number remains constant throughout the game until the player guesses it correctly.
- Initialize the Attempt Counter:
- attempts = 0: Sets the initial count of attempts to zero. Each player guess will increment this counter.
- The Game Loop (while True):
- This while loop will continue to run until the player guesses the correct number, at which point break will end the loop.
- Inside the loop:
- Input Handling:
- guess = int(input(“Make a guess: “)): Prompts the player for their guess and converts it to an integer.
- attempts += 1: Increments the attempt counter with each guess.
- Guess Checking:
- if guess < target_number: Checks if the guess is lower than the target and, if so, prints a hint (“Too low. Try again!”).
- elif guess > target_number: Checks if the guess is higher than the target and, if so, prints a hint (“Too high. Try again!”).
- else: If the guess matches the target number, it means the player guessed correctly:
- print(f”Congratulations! You guessed the number {target_number} in {attempts} attempts.”): Displays a congratulatory message showing the correct number and the total attempts.
- break: Exits the loop, ending the game since the correct number has been guessed.
- Input Handling:
- Handling Invalid Input with try-except:
- try-except block catches non-integer input (e.g., letters or symbols) and prevents the program from crashing:
- If a ValueError occurs (meaning the input is not an integer), it prints Please enter a valid integer. and prompts the player to guess again without affecting the attempts counter.
- try-except block catches non-integer input (e.g., letters or symbols) and prevents the program from crashing:
Sample Game Play
Here’s an example of what the game’s output might look like:
Welcome to the Higher-Lower Game! I'm thinking of a number between 1 and 100. Make a guess: 99 Too high. Try again! Make a guess: 51 Too low. Try again! Make a guess: 75 Too high. Try again! Make a guess: 63 Too low. Try again! Make a guess: 68 Too high. Try again! Make a guess: 65 Too high. Try again! Make a guess: 64 Congratulations! You guessed the number 64 in 7 attempts.
Summary
- The game generates a random number between 1 and 100.
- The player guesses until they find the correct number, receiving hints of “Too high” or “Too low” after each incorrect guess.
- The game counts attempts and displays the total at the end.
- The try-except block ensures the game only accepts valid integers, providing a smoother experience for the player.