Higher-Lower Game with Python


The Higher−Lower game is a classic and entertaining guessing game that challenges players to guess a randomly generated number within a specified range. By implementing this game using the Python programming language, beginners can gain valuable coding experience while creating an interactive and enjoyable gaming experience.

In this article, we will explore the step−by−step process of creating a Higher−Lower game with Python, providing detailed explanations and code examples along the way. Whether you're a novice programmer looking to enhance your skills or simply seeking a fun coding project, this article will guide you through the development of a fully functional Higher−Lower game that will engage and entertain players of all ages.

Understanding the Rules

Before diving into the implementation, let's have a deeper understanding of the rules of the Higher−Lower game. The game begins by generating a random number within a predefined range, such as between 1 and 100. The player's objective is to guess this randomly generated number. After each guess, the game provides feedback on whether the guessed number is higher or lower than the actual number. Based on this feedback, the player adjusts their subsequent guesses. The player continues to make guesses until the correct number is found.

Setting Up the Game

In order to build the Higher−Lower game, we must first establish a few preparatory elements. We must first import the random module before we can generate a random number. We also define the parameters that will be utilized to generate the random number. Let us show the lower bound as 1 and the upper bound as 100. We also initialize the number_of_guesses variable, which will be used to track the total number of guesses made by the player.

import random

lower_bound = 1
upper_bound = 100
number_of_guesses = 0

Generating the Random Number

To create a random number within the given range, we can use the random.randint() function from the random module. This function takes the lower and upper bounds as parameters and returns a random integer between them.

random_number = random.randint(lower_bound, upper_bound)

Taking User Input

To allow the player to make guesses, we need to capture their input. We achieve this by using the input() function, which prompts the player to enter a number. Since the input() function returns a string, we convert the input to an integer using the int() function.

guess = int(input("Guess the number: "))

Comparing the Guess

After receiving the player's guess, we need to compare it with the randomly generated number. We can use an if−else statement to provide feedback based on the comparison. If the guess is equal to the random number, the player wins the game. Otherwise, we inform the player if the guess is higher or lower than the actual number and provide another chance to make a guess.

if guess == random_number:
    print("Congratulations! You guessed the number correctly.")
else:
    if guess < random_number:
        print("The number is higher!")
    else:
        print("The number is lower!")
    number_of_guesses += 1

Looping the Game

We enclose the input and comparison steps within a while loop to enable the player to make multiple guesses until they find the correct number. We set a condition for the loop to continue until the player guesses the correct number.

while guess != random_number:
    guess = int(input("Guess the number: "))
    
    if guess < random_number:
        print("The number is higher!")
    else:
        print("The number is lower!")
        
    number_of_guesses += 1

Displaying the Results

Finally, after the player successfully guesses the number, we display the number of attempts they took to win the game.

print("Congratulations! You guessed the number correctly in", number_of_guesses, "attempts.")

Putting It All Together

Here is the complete code for the Higher−Lower game:

import random

lower_bound = 1
upper_bound = 100
number_of_guesses = 0

random_number = random.randint(lower_bound, upper_bound)

guess = int(input("Guess the number: "))

while guess != random_number:
    if guess < random_number:
        print("The number is higher!")
    else:
        print("The number is lower!")
        
    number_of_guesses += 1
    guess = int(input("Guess the number: "))

print("Congratulations! You guessed the number correctly in", number_of_guesses, "attempts.")

Output

Guess the number: 50
The number is higher!
Guess the number: 75
The number is lower!
Guess the number: 60
The number is higher!
Guess the number: 65
The number is lower!
Guess the number: 63
Congratulations! You guessed the number correctly in 4 attempts.

Error Handling

We want to ensure that the player provides a correct guess inside the set range in the Higher−Lower game. We can create error management using a try−except block to handle potential errors when the player enters an erroneous value.

try:
    guess = int(input("Guess the number: "))

    if guess < lower_bound or guess > upper_bound:
        raise ValueError("Invalid guess. Please enter a number within the range.")

except ValueError as e:
    print(str(e))

In the above code snippet, we use the try block to attempt to convert the user's input into an integer. If the conversion is successful, we proceed with the comparison as before. However, if an error occurs during the conversion, a ValueError is raised.

We use the except block to catch the ValueError and handle it gracefully. In this case, we print an error message to notify the player that their guess is invalid and ask them to enter a number within the specified range.

By implementing error handling, we improve the user experience by preventing crashes or unexpected behaviors caused by invalid inputs. It also allows us to guide the player in making correct and meaningful guesses within the game.

Here's the updated code snippet with error handling:

try:
    guess = int(input("Guess the number: "))

    if guess < lower_bound or guess > upper_bound:
        raise ValueError("Invalid guess. Please enter a number within the range.")

    if guess == random_number:
        print("Congratulations! You guessed the number correctly.")
    else:
        if guess < random_number:
            print("The number is higher!")
        else:
            print("The number is lower!")
        number_of_guesses += 1

except ValueError as e:
    print(str(e))

Conclusion

In conclusion, creating a Higher−Lower game with Python is a fantastic way to strengthen your coding skills while providing an engaging and interactive experience. By following the steps outlined in this article, you can develop a fully functional game that challenges players to guess a randomly generated number within a given range. Through the use of loops, conditional statements, and input/output functions, you have learned how to implement the game's core mechanics. The Higher−Lower game not only offers an enjoyable gaming experience but also serves as an excellent introduction to programming concepts. So, get ready to embark on the exciting journey of creating your own Higher−Lower game and have fun exploring the possibilities of Python programming.

Updated on: 20-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements