Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Creating A Guessing Game In Python

5 min read

A guessing game is a classic and fun way to engage users and challenge their guessing skills. In this article, we will walk you through the process of creating a simple guessing game using Python. This game will randomly generate a number, and the user will have to guess the number within a certain range.

This is going to be a simple guessing game where the computer will generate a random number between 1 to 10, and the user has to guess it in 5 attempts.

Based on the user's guess computer will give various hints if the number is high or low. When the user guess matches the number computer will print the answer along with the number of attempts.

Let's get started!

Getting Started

To create the guessing game, we'll be using Python, so make sure you have Python installed on your system. You can use any Python IDE or a simple text editor to write the code.

The Game Logic

The Number Guessing Game revolves around a few key elements:

  1. Generating a Random Number: The game will randomly generate a number between 1 and 10, which you will have to guess.

  2. User Interaction: You will be asked to enter your name, making the game more personalized. Then, you can begin guessing the number.

  3. Feedback Loop: After each guess, the game will provide feedback on whether your guess is too low or too high. This will guide you in making your subsequent guesses.

  4. Limited Attempts: You will have a maximum of 5 attempts to guess the correct number. Can you solve the mystery within these attempts?

  5. Victory or Defeat: If you successfully guess the number within the given attempts, you will be celebrated for your guessing prowess. If not, the game will reveal the correct number.


This is how the game looks in action,

Hello, What's your name?
Abhijeet
okay! Abhijeet I am Guessing a number between 1 and 10:
2
Your guess is too low
4
Your guess is too low
6
You guessed the number in 3 tries!

Creating Guessing Game with Python

Now, open your favorite text editor and start coding.

First, we will create a file a new file named game.py from our text editor.

To generate a random number we will use a Python module named random to use this module in our program, we first need to import it.

 import random
Next, we will use the random module to generate a number between 1 to 10 and store it in a variable named number.
number = random.randint(1, 10)

Now we will prompt the user to enter his name and store it to a variable named player_name.

player_name = input("Hello, What's your name?")

In the next step, we will create a variable named number_of_guesses and assign 0 to it. Later we will increase this value on each iteration of the while loop.

Finally, before constructing the while loop, we will print a string which includes the player name.

 print('okay! '+ player_name+ ' I am Guessing a number between 1 and 10:')

Now let's design the while loop.

while number_of_guesses < 5:
        guess = int(input())
        number_of_guesses += 1

        if guess < number:
            print('Your guess is too low.')
        elif guess > number:
            print('Your guess is too high.')
        else:
            break

In the first line, we are defining the controlling expression of the while loop. Our game will give user 5 attempts to guess the number, hence less than 5 because we have already assigned the number_of_guesses variable to 0.

Within the loop, we are taking the input from the user and storing it in the guess variable. However, the user input we are getting from the user is a string object and to perform mathematical operations on it we first need to convert it to an integer which can be done by the Python's inbuilt int() method.

In the next line, we are incrementing the value of number_of_guesses variable by 1.

Below it, we have 3 conditional statements.

  1. In the first, if statement we are comparing if the guess is less than the generated number if this statement evaluates to true, we print the corresponding Guess.
  2. Similarly, we are checking if the guess is greater than the generated number.
  3. The final if statement has the break keyword, which will terminate the loop entirely, So when the guess is equal to the generated number loop gets terminated.

Below the while loop, we need to add another pair of condition statements,

if guess == number:
        print('Congratulations, ' + player_name + '! You guessed the number in ' + str(number_of_guesses) + ' tries!')
    else:
        print('Sorry, ' + player_name + ', you did not guess the number. The number was ' + str(number))

Here we are first verifying if the user has guessed the number or not. if they did, then we will print a message for them along with the number of tries.

If the player couldn't guess the number at the end we will print the number along with a message.

Guessing Game Program In Python

If you have been following us, then this is how your program should look like:

import random

def number_guessing_game():
    number = random.randint(1, 10)

    player_name = input("Hello, What's your name? ")
    number_of_guesses = 0

    print("Okay, " + player_name + "! I am guessing a number between 1 and 10:")

    while number_of_guesses < 5:
        guess = int(input())
        number_of_guesses += 1

        if guess < number:
            print('Your guess is too low.')
        elif guess > number:
            print('Your guess is too high.')
        else:
            break

    if guess == number:
        print('Congratulations, ' + player_name + '! You guessed the number in ' + str(number_of_guesses) + ' tries!')
    else:
        print('Sorry, ' + player_name + ', you did not guess the number. The number was ' + str(number))

Now let's run our game!

To run the game, type this in your terminal python game.py and hit Enter.

This was it, if you got stuck somewhere grab the code form Github repo

How the Game Works

  1. Upon starting the game, a random number between 1 and 10 is generated using random.randint(1, 10).

  2. You will be asked to enter your name, making the game more personalized and engaging.

  3. The game will prompt you to make a guess, and it will provide feedback based on your guess - whether it's too low or too high.

  4. You have 5 attempts to guess the correct number. Can you crack the code within these attempts?

  5. If you guess the number correctly, the game will congratulate you and display the number of attempts it took. If not, the game will reveal the correct number.

Conclusion

Congratulations! You have successfully created a fascinating Number Guessing Game using Python. This interactive game challenges your intuition and keeps you engaged as you try to guess the random number within the specified range.

Feel free to modify the game according to your preferences. You can adjust the range of numbers, increase or decrease the number of attempts, or add more features to enhance the gameplay.

So, are you up for the challenge? Test your guessing skills and have fun playing the Number Guessing Game in Python!


PYTHON

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read