• Get application security done the right way! Detect, Protect, Monitor, Accelerate, and more…
  • You should have already guessed the content of this article. And you should probably be familiar with number guessing and looking for a way to built it using Python.

    Let’s learn to create a number guessing game from scratch.

    Number Guessing Game

    The game is simple. The user has to guess the randomly generated number that lies between the range from 1 to 100. That’s it.

    Is the game that simple?

    Yeah, it is.

    But, there is one thing that we have to provide to the users to guess the number. That’s hints. We have to provide a message to the user saying the current guessed number is less than the correct number or the current guessed number is greater than the correct number. So that users will know in which direction they have to go.

    We can make it more exciting by adding extra features like maximum number of chances to guess, increasing the range, setting a timer, etc..,

    Creating the basic working game is mandatory. After it, we can add more features as discussed. So, we are going to create the basic version of the game in this section. And then we will move to add new features.

    I want you to try creating the game without blindly copying the code. So, I am going to explain the algorithm first. It will help you to code yourself or understand the code quickly.

    Let’s see the algorithm to create the Number guessing game.

    Algorithm

    Make sure you understand the algorithm before moving to the coding part.

    • Define the range of the numbers. By default, it’s 1-100 but you can change it as you prefer.
    • Generate a random integer from the above range (1-100).
    • Start the game by displaying the user a message saying “Guess the number from X to Y”. You may update the message as you wish.
    • Initialize a variable to 0 to count the total number of chances that the user has taken to guess the number correctly.
    • Write an infinite loop.
      • Ask the user to guess the number.
      • If the current guessed number is equal to the randomly generated number, then congratulate the user with a message as you like. An example would be “-> Hurray! You got it in 5 steps!”.
      • Break the loop after congratulating the user.
      • If the current guessed number is less than the randomly generated number, then give a message to the user saying “-> Your number is less than the random number” or a custom message having the same meaning.
      • If the current guessed number is greater than the randomly generated number, then give a message to the user saying “-> Your number is greater than the random number” or a custom with the same meaning.
      • Finally, increment the chances that the user has taken to guess.

    You would have got code in your mind after seeing the algorithm. Don’t worry even if you don’t get the complete code. But, make sure you understand the above algorithm.

    It’s time to get our hands to work with code. Get into the code without further ado.

    Code

    Did you try to write the code?

    If yes and completed it. It’s great. Check out the code and understand it to add more perspectives to your knowledge.

    Don’t worry even if you didn’t write the code. See the below code and understand it. Try to tweak and write it in your own way for better understanding.

    So, let’s see the code.

    import random
    
    
    class NumberGuessingGame:
    
        def __init__(self):
            ## define the range
            self.LOWER = 1
            self.HIGHER = 100
    
        ## method to generate the random number
        def get_random_number(self):
            return random.randint(self.LOWER, self.HIGHER)
    
        ## game start method
        def start(self):
            ## generating the random number
            random_number = self.get_random_number()
    
            print(
                f"Guess the randomly generated number from {self.LOWER} to {self.HIGHER}")
    
            ## heart of the game
            chances = 0
            while True:
                user_number = int(input("Enter the guessed number: "))
                if user_number == random_number:
                    print(
                        f"-> Hurray! You got it in {chances + 1} step{'s' if chances > 1 else ''}!")
                    break
                elif user_number < random_number:
                    print("-> Your number is less than the random number")
                else:
                    print("-> Your number is greater than the random number")
                chances += 1
    
    ## instantiating and starting the game
    numberGuessingGame = NumberGuessingGame()
    numberGuessingGame.start()
    

    There are some things that you understand from the code.

    • The range is defined inside the __init__ method so that it can be used across the class methods.
    • We can easily change it in one place that changes across the app accordingly.
    • There is a separate method to generate the random number which follows the principle of “separate the concerns”. Here, our method has little code, but it might increase in the future.
    • Finally, we have used class so that every method that’s related to the game will reside inside it. And it can be easily reused in some other apps.

    All the points that are discussed above are related to writing clean code. We should try to write the clean code that you understand even after some years.

    The sample output of the game looks as follows.

    $ python number_guessing_game.py 
    Guess the randomly generated number from 1 to 100
    Enter the guessed number: 50
    -> Your number is less than the random number
    Enter the guessed number: 75
    -> Your number is less than the random number
    Enter the guessed number: 90
    -> Your number is greater than the random number
    Enter the guessed number: 85
    -> Your number is greater than the random number
    Enter the guessed number: 80
    -> Hurray! You got it in 5 steps!

    I assume you have Python installed to try the above code.

    Extra Feature

    We are going to add the maximum number of chances that a user gets to guess the number. If the user doesn’t guess the number within the number of chances, then the user loses.

    How do we add it?

    It’s a simple two-step process. Let’s see the steps.

    • Define the maximum number of chances that the user gets to guess the number.
    • Check whether the user has chances or not before asking for the input. And end the game if the user is out of given chances.

    The following code additional will complete the feature.

    • Add the following code inside the __init__ method.
    self.MAX_CHANCES = 10
    • Add the following condition before the user enters the next guess.
    if chances == self.MAX_CHANCES:
                    print("-> Phew! You lost the game. You are out of chances")

    Now, try the game without guessing the correct number. You should see a similar output as follows.

    $ python number_guessing_game.py 
    Guess the randomly generated number from 1 to 100. You have 10 chances to guess.
    Enter the guessed number: 1
    -> Your number is less than the random number
    Enter the guessed number: 2
    -> Your number is less than the random number
    Enter the guessed number: 3
    -> Your number is less than the random number
    Enter the guessed number: 4
    -> Your number is less than the random number
    Enter the guessed number: 5
    -> Your number is less than the random number
    Enter the guessed number: 6
    -> Your number is less than the random number
    Enter the guessed number: 7
    -> Your number is less than the random number
    Enter the guessed number: 8
    -> Your number is less than the random number
    Enter the guessed number: 9
    -> Your number is less than the random number
    Enter the guessed number: 10
    -> Your number is less than the random number
    -> Phew! You lost the game. You are out of chances

    Hurray! we have added an extra feature to our game. It’s not the end though. You can add some more features to make it more engaging to the users. It’s your time now. Go ahead and make it more beautiful :).

    Conclusion

    We have created a simple number guessing game. Now, it’s your turn to think of games that you were playing when you were young. Make them using programming language and share with your friends. We can digitalize most of our childhood games.

    Next, explore Python IDE and online compiler to run Python code.

    Happy Coding 🙂