IBepyProgrammer

How to Build a Number-Guessing Game using Python

3 min read
How to Build a Number-Guessing Game using Python

In this tutorial, we will learn how to build a random number game in Python. In the example, we will use the random module in Python to generate random integers, select the difficulty of the game, and try again once we have reached the maximum number of entries for the game.

Step 1

For this tutorial, I will be using Jupyter Notebook but any other editor will work. To begin, we will import the random module into our Jupyter Notebook cell.

import random

Step 2

We will then define a function that will take two arguments. These are "limit", which is the maximum number of tries the player gets to enter a number, and the "number", which is the number we will pass into the levels.

def number_guessing(limit, number):
    # From the random module we use "randint" to generate a random integer number
    random_num = random.randint(1, number)
    try:
        while limit > 0:
            guess = int(input("Enter your gurss: "))
            limit -=1
            if random_num == guess:
                print("You are Correct!")
                break
            elif guess > number:
                print("Try again!")
                print(f"You have {limit} tries")
            else:
                print("Sorry, You Failed!")
                print(f"You have {limit} tries")
        print("Game Over")
        print(f"The random number was {random_num}")
    except ValueError:
        print("Enter Integers only!") 
  • In the code above, the program will execute the try block of code. If there is an error in the try block, The except block of code is executed instead.

Step 3

We then create three functions that will be called to allow the player to pick the difficulty of the game. In this example, we will call the function above named "number_guessing()". The first argument in the parenthesis gives the number of attempts the player is given to guess a number while the second argument in the parenthesis gives the maximum range of the number entered by the player.

def easy():
    print("Guess a number between 1 and 10. You only have 5 tries")
    number_guessing(5, 10)
    
def medium():
    print("Guess a number between 1 and 20. You only have 4 tries")
    number_guessing(4, 20)
    
def hard():
    print("Guess a number between 1 and 50. You only have 3 tries")
    number_guessing(3, 50)

Step 4

In the block of code below, we will create a function that will allow the user to quit the game when they run out of tries and or if they guess correctly.

def try_again():
    retry = input("Do you want to try again? Y/N")
    if retry.upper() == "Y":
        welcome()
    elif retry.upper() == "N":
        print("Thanks for playing")
    else:
        print("Enter Y / N")
        try_again()  

Step 5

We can then create a function that allows the player to pick the difficulty of the game. The player is given the option to pick between "Easy", "Medium", and "Hard". Note that we call the "try_again()" function above to allow for the game to be restarted at a different difficulty level or quit the game. We also call the functions "easy()", "medium()" and "hard()". If the user does not pick any of the options within the difficulty range, they are prompted to try again and pick a valid difficulty level.

def welcome():
    print("Let's Play a Guessing Game!")
    level = input("Choose your level. Easy, Medium, Hard")
    if level.upper() == "EASY":
        easy()
        try_again()
        
    elif level.upper() == "MEDIUM":
        medium()
        try_again()
        
    elif level.upper() == "HARD":
        hard()
        try_again()
        
    else:
        print("Invalid Input")
        welcome()

Step 5

To start playing the game, we need to call the function named "welcome()".

welcome()

Conclusion

In this short article, we learn how to use the random module to build a simple number guessing game with different difficulty levels. In future articles, we will dive deeper into functions in Python and the random module in order to demonstrate how to use it in different applications.

If you found this article helpful consider subscribing and sharing. A copy of the working code can also be found on my Git hub repository. https://github.com/IBepyProgrammer/Python-number-guessing-game/blob/main/Number Game.ipynb

Thank you.

Sign up for our newsletter

Don't miss anything. Get all the latest posts delivered to your inbox. No spam!