130
In this tutorial, we will create a simple Higher-Lower Game using Python.
The game will involve:
- The computer randomly selecting a number between a predefined range (e.g., 1 to 100).
- The player attempting to guess the number.
- The program giving feedback on whether the guess is too high or too low.
- The game continuing until the player guesses the number correctly.
Let's break the game down step by step.
Step 1: Import the Required Modules
We will need the random module to generate a random number, and we'll use basic input and print functions for user interaction.
import random
Step 2: Define the Game Logic
The main logic of the game involves:
- Generating a random number.
- Getting the player's guess.
- Providing feedback on whether the guess is higher or lower than the target number.
- Repeating the guessing process until the correct guess is made.
Code Outline:
- Generate a random number using random.randint().
- Use a while loop to repeatedly ask the player for their guess.
- Give hints after each incorrect guess (whether the guess is too high or too low).
- End the game when the correct number is guessed.
Step 3: Complete Code
Here’s the complete Python code for the Higher-Lower game:
import random def higher_lower_game(): # Step 1: Generate a random number between 1 and 100 number_to_guess = random.randint(1, 100) attempts = 0 # Track the number of attempts print("Welcome to the Higher-Lower Game!") print("I have selected a number between 1 and 100. Can you guess it?") # Step 2: Start the guessing loop while True: try: # Step 3: Get the user's guess guess = int(input("Enter your guess: ")) attempts += 1 # Increment the number of attempts # Step 4: Check if the guess is correct 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've guessed the number {number_to_guess} in {attempts} attempts.") break # End the game when the correct guess is made except ValueError: print("Please enter a valid integer.") # Handle non-integer input # Step 5: Run the game higher_lower_game()
Step-by-Step Explanation:
- random.randint(1, 100):
- This generates a random number between 1 and 100, which the player must guess.
- while True::
- The game runs in an infinite loop until the player guesses the correct number. This ensures that the guessing process continues until the player wins.
- Player's Guess Input:
- int(input(“Enter your guess: “)): This prompts the player to input their guess. The input is converted to an integer.
- Error handling: The try-except block ensures that if the player enters something other than a number (e.g., a string), the program will catch the error and prompt the user to enter a valid integer.
- Feedback:
- If the player's guess is too low (guess < number_to_guess), the program prints “Too low! Try again.”
- If the guess is too high (guess > number_to_guess), the program prints “Too high! Try again.”
- When the player guesses correctly, the program prints a congratulatory message, including the number of attempts it took.
- Attempts Counter:
- The variable attempts is used to keep track of how many guesses the player has made.
- End of the Game:
- The loop terminates when the player guesses the correct number, and the break statement is used to exit the loop.
Example Run
Python 3.7.9 (bundled) >>> %Run hilo.py Welcome to the Higher-Lower Game! I have selected a number between 1 and 100. Can you guess it? Enter your guess: 50 Too low! Try again. Enter your guess: 75 Too high! Try again. Enter your guess: 63 Too low! Try again. Enter your guess: 69 Too high! Try again. Enter your guess: 66 Too low! Try again. Enter your guess: 67 Congratulations! You've guessed the number 67 in 6 attempts.
Customizing the Game
Here are a few ideas to enhance or customize the Higher-Lower game:
- Change the range: You can modify the range of numbers (e.g., between 1 and 1000) to make the game harder or easier.
number_to_guess = random.randint(1, 1000)
- Limit the number of attempts: You could limit the number of guesses allowed to increase difficulty.
max_attempts = 10 while attempts < max_attempts: # Game logic
- Provide hints: After a certain number of incorrect guesses, provide additional hints, such as whether the number is even or odd.
Conclusion
In this tutorial, we built a Higher-Lower Game in Python using basic concepts like:
- Random number generation (random.randint()).
- Loops (while True).
- Conditional statements (if-elif-else).
- Exception handling (try-except).