Build a Number Guessing Game in Python

This is a tutorial where you will learn how to create your own number guessing game in Python with the complete code. This is actually a game that can be played with a computer with numbers.

number guessing game in python

The rule of this game

The computer will choose any random number between 1 to 100. Then the user will try to guess the right number.

If the user failed to enter the random number chosen by the computer then the user will get a hint.

The hints will be like these as you can see below:

Your guess was low, please enter a higher number

Your guess was high, please enter a lower number

With the help of these hints, the user has to find the random number chosen by the computer.

When the user will enter the right random number chosen by the computer he/she will get an output like this:

You won!

Number of turns you have used: n

n will be the number of turns the user used to guess the right random number chosen by the computer.

I hope you have understood the rule.

Python program for this number guessing game

Here is the complete Python Source code of the guess the number game below:

# guess the number game in Python by CodeSpeedy.com
import random
random_number = random.randint(1,100)
win = False
Turns =0
while win==False:
    Your_guess = input("Enter a number between 1 and 100")
    Turns +=1
    if random_number==int(Your_guess):
        print("You won!")
        print("Number of turns you have used: ",Turns)
        win == True
        break
    else:
     if random_number>int(Your_guess):
        print("Your Guess was low, Please enter a higher number")
     else:
        print("your guess was high, please enter a lower number")

I have played this game and here is its output:

Enter a number between 1 and 100 50
Your Guess was low, Please enter a higher number
Enter a number between 1 and 100 75
your guess was high, please enter a lower number
Enter a number between 1 and 100 65
your guess was high, please enter a lower number
Enter a number between 1 and 100 60
You won!
Number of turns you have used: 4

Process finished with exit code 0

Explanation of Number guessing game in Python

import random

This will import the random module in our Python program.

In Python random.randint(1,100) will return a random number in between 1 to 100.

Here win is a boolean variable. This variable is used to check if the user entered the right random number chosen by the computer or not. When the user chooses the random number chosen by the computer the win variable will be set to true

The rest of the program is standing on the if else statement to check if the user entered the right random number or not.

You can extend the functionality of this game if you wish by providing your own Python code.

I can give you some suggestions for that.

  • You can create a scoring system using the number of turns. The more less the number of tuts, the more score the user will able to collect.
  • Also, you can set the limitations for the number of turns that can be used to guess the random number. After reaching the limitation, the game will be over. To achieve this feature, you have to write your own program wisely.

Below is given two other tutorials for number-guessing games done in different programming languages:

You can check the algorithms to extend the features

7 responses to “Build a Number Guessing Game in Python”

  1. djimbob says:

    This code is very bad python code.

    1. Incorrectly used equality operator (==) while attempt to assign to the variable win. Variable assignment in python is never done with double equals (==) and in python is done with (=).
    2. Python coding standards dictate variable names should be in all lowercase. So you should change Your_guess and Turns to your_guess and turns.
    3. The break statement is completely unnecessary (without the earlier error).
    4. It doesn’t gracefully handle entering things that can’t be cast to integers. You should wrap the int(your_guess) in a try-except clause that checks for ValueError.
    5. Python coding standards state you should put single spaces around comparison operators (== and >).
    6. Inconsistent capitalization in messages to users. If the guess is too low then “Your”, “Guess”, and “Please” are capitalized, but are not capitalized if the guess is too high.

  2. Saruque Ahamed Mollick says:

    Thanks for the Python standard reminding. I am making changes to this code.

    Your modification to this code is like this:
    import random
    random_number = random.randint(1,100)
    won = False
    turns = 0
    while not won:
    try:
    guess = input(“Enter a number between 1 and 100: “)
    guess = int(guess)
    except ValueError:
    print(“The following is not a valid number: “, guess)
    print(“Please try again.”)
    continue
    turns += 1
    if random_number == guess:
    print(“You won!”)
    print(“Number of turns you have used: “, turns)
    won = True
    elif random_number > guess:
    print(“Your guess was low, please enter a higher number”)
    else:
    print(“Your guess was high, please enter a lower number”)

  3. Eric D says:

    #Try to correct it that way, embedding the if command into the try, except, else command, I’m not sure whether you’d like the turns also to be counted if they give a ValueError, I included the case that it will add an +1 turn regardless of ValueError.

    won = False
    turns = 0
    while not won:
    guess = input(“Enter a number between 1 and 100: “)
    turns += 1
    try:
    guess = int(guess)
    except ValueError:
    print(“The following is not a valid number: “, guess)
    print(“Please try again.”)
    else:

    if random_number == guess:
    print(“You won!”)
    print(“Number of turns you have used: “, turns)
    won = True
    elif random_number > guess:
    print(“Your guess was low, please enter a higher number”)
    else:
    print(“Your guess was high, please enter a lower number”)

  4. Anisha says:

    import random

    logo = ”’.—-, ,—–,–, _.—.,_ ,–,—-. _.—.,_ ,-.–. _.—.,_ ,–,—.
    / “–`.-, | ‘- -\==\ .’ – , `.-, /==/ .=. \ .’ – , `.-, / – \==\ .’ – , `.-, /==/ – ` \
    ‘-._ -|==| \,–, ‘/==/ / – , ,_\==\ \==\ ‘=’\ \/ – , ,_\==\ / /\/==/ / – , ,_\==\\==\/\ – |
    .-.’ |==| / /==/ | .=. |==| `–`–‘/ `/ .=. |==| | \==\ | .=. |==|`–`/ `/
    \ , _\==\ / -/==/ | – :=; : _|==| /==/ -/| – :=; : _|==| / `-.`-.| – :=; : _|==| |==| |
    `-. |==| / -/==/ | `=` , |==| /==/ -/ | `=` , |==| `–. \==\ `=` , |==| `–`–`
    _.-‘, _|==| / `\==\_,–,\ _, – /==/ /==/- / \ _, – /==/ .-/ /==/\ _, – /==/ .=.
    \ , \==\ /` – ,/==/ `. – .`=.` \==\ / `. – .`=.` / /==/ `. – .`=.` :=; :
    “—–‘–‘ `——`–` “–‘–‘ `-‘` “–‘–‘ `—–`-` “–‘–‘ `=`
    ”’
    print(logo)
    print(“Welcome to the Number Guessing Game!”)
    print(“I am thinking of a number between 1 to 100.”)
    diff = input(“Choose a difficulty: ‘HARD’ or ‘EASY'”).lower()
    random_num = random.randint(1, 100)
    print(random_num)
    if diff == “easy”:
    def leveleasy():
    print(“You have 6 attempts remaining.”)
    win = False
    lives = 6
    while not win:
    attempt = int(input(“Guess the number: “))
    if attempt != random_num:
    lives -= 1
    if attempt > random_num:
    print(f”Too high.\nGuess again.\nYou have {lives} remaining.”)
    elif attempt random_num:
    print(f”Too high.\nGuess again.\nYou have {lives} remaining.”)
    elif attempt < random_num:
    print(f"Too low.\nGuess again.\nYou have {lives} remaining.")

    if lives == 0:
    win = False
    print("You lose.")
    break
    elif attempt == random_num:
    win = True
    print("You win.")

    levelhard()

  5. Nurhidayah Binti Ismail says:

    Can help me? Create a Python program in which the computer randomly chooses a number between 1 to 10, 1 to 100, or any
    range. Then give users a hint to guess the number. Every time the user guesses wrong, he gets another clue, and
    his score gets reduced. The clue can be multiples, divisible, greater, or smaller, or a combination of all. You will
    also need functions to compare the inputted number with the guessed number, to compute the difference between
    the two, and to check whether an actual number was inputted or not in this Python project.

  6. kishore kumar says:

    theoritical contents can be improved

  7. clark says:

    what if I want to exit the game? like
    we leave the game without guessing the number.

Leave a Reply

Your email address will not be published. Required fields are marked *