Python Number Guessing Game

In this Python tutorial, we will learn how to create Python Number Guessing Game. We have started from basic and went all the way to the advanced ways of creating this application. Also, we have covered these topics.

  1. Python Number Guessing Game Overview
  2. Python Number Guessing Game While Loop
  3. Python Number Guessing Game For Loop
  4. Python Random Number Guessing Game
  5. Python Number Guessing Game Code
  6. Number Guessing Game Python Tkinter
  7. Number Guessing Game Python Project

Python Number Guessing Game Overview

In this section, we will cover brief information about the Python number guessing game.

python tkinter number guessing game
  • In this game, the program generates random number but this number is not visible to the player.
  • Player tries to guess the number. If the player enters the same number that is generated by system then program displays the winning message and game ends there.
  • If the player enters wrong number then that number is evaluated. If the number is greater than right answer than system gives a hint that entered number is ‘high’ otherwise if number is smaller than right answer than it says ‘lower’.
  • There are limited number of attempts available with the user to win the game.
  • Here is the basic demonstration of python number guessing game. In this game correct answer is 7 and user has unlimited chances to guess the number.
Python Number Guessing Game Overview
Python Number Guessing Game Overview

Read If not condition in python

Python Number Guessing Game While Loop

In this section, we will learn about the python number guessing game while loop. We will understand the need for a while loop in the game.

  • There are two types of loops used in python. ‘for’ loop and ‘while’ loop.
  • ‘for’ loop is mostly used when we know how many times we have to execute the loop. In next section, we have discussed more about ‘for’ loop.
  • ‘While’ loop is mostly used when we have to run the loop infinite times. For example, if we want to give unlimited chances to guess the number in this game then we will use while loop.
  • Please note that while loop is used not only when we have to run infinite loop there are other purposes too. We mentioned this in the previous statement because we will run infinite loop using while statement.
  • In our example, we will keep on running the program until and unless the user guesses the right answer.

Source Code:

In this source code, we have started an infinite loop using ‘while’ loop. This loop will be terminated only when the user will give the right answer.

run is the flag that is marked True which means the loop will keep on running. When the user will enter the right answer then this flag is turned to False and the loop will end there.

run = True
while run:
    user_input = int(input('Enter Number: '))
    if user_input == 7:
        print('You won!')
        run = False
    else:
        print('try again!')
        continue

Output:

In this output, the program keeps on prompting for numbers till the time right answer is not provided by the player.

Python Number Guessing Game Overview
Python Number Guessing Game While Loop

Read Download zip file from URL using python

Python Number Guessing Game For Loop

In this section, we will understand about python number guessing game using ‘for’ loop. We will explore the ways of using for loop in the guessing game.

  • ‘For’ loop runs for the finite time. In other words, if we know how many times we have to run the loop in that case we can use ‘for’ loop.
  • It’s all about the preference and complexity otherwise same task can be done with while loop aswell.
  • In our Python number guessing game we will use for loop to limit the number of attempts by the player.
  • We will provide 5 chances to guess the right answer after that game will be over and player will loose.

Source Code:

In this source code, we have a limited number of attempts to 5 times only and the correct answer is 7.

Each time player makes a wrong guess, a try again message with a remaining number of attempts is displayed on the screen.

attempt = 5
for i in range(5):
    user_input = int(input('Enter Number: '))

    if user_input == 7:
        print('You won!')
        break
    else:
        print(f'Try again! {attempt} left.')
        attempt -= 1
        continue
    

Output:

In this output, On entering 7 the program ends with the Won! message. But for remaining attempts ‘try again’ message is displayed with a remaining number of attempts.

Python Number Guessing Game for Loop
Python Number Guessing Game For Loop

Read Python Return Function

Python Random Number Guessing Game

In this section, we will learn about Python Random Number Guessing Game.

  • Random number can be generated using python random module. Since we want to generate only integer number so we will use randint() method of random module.
  • Python random.randint()method accepts starting and end numbers. Then it generates any number between this range.
  • So far we were hard coding the result as 7 in above programs but from now onwards we will generate a random number using python random module.
random.randint(0, 10)
  • This is an example of implentation on Python random.randint() method. Here 0 is the starting point (upper bound) and 10 is end point (lower bound).
  • Every time the program will run, it will show random numbers between 0 to 10.

Source Code:

In this code, we have used a random module to generate random numbers that the player has to guess.

import random

num = random.randint(0, 10)
print('Number:',num)
attempt = 4 
msg = 'You Lost!'   

while attempt > 0:
    user_input = int(input('Enter Number: '))

    if user_input == num:
        msg = 'You Won!'
        break
    else:
        print(f'Try again! {attempt} attempt left.')
        attempt -= 1
        continue

print(msg)

Output:

This output is executed twice so please watch it completely. Each time the program generates a random number that we have to guess. To make things simpler we have displayed the answer as well.

python random number guessing game
Python Random Number Guessing Game

Read How to convert an integer to string in python

Python Number Guessing Game Code

In this section, we have created a python number guessing game script. This is going to be a command-line-based game. We have created GUI based game in the next section.

  • Random method is used to generate random number that player need to guess inorder to win the game.
  • In the below code, you can see that random number ranges between 0 to 10. You can change this range as per your need.
import random

num = random.randint(0, 10)
print(f'''
---------------------------
Correct answer: {num}
---------------------------
''')
  • We have limted the number of attempts to 5. Though in the below code it is mentioned 4 if you will run the program it will give you extactly 5 attempts.
  • msg is set to empty string because we will update this empty list later in code to display the message.
attempt = 4
msg = ''
  • In the remaining code, first we have assured that attempts are not 0.
    while attempt > 0 if the attempt is 0 that means player has lost the game.
  • To accept continuos input, we have put the input statement inside the while loop.
  • If-else condition is used to compare the user input with the random generated number.
  • If the number matches then player wins the game and program ends there. But if the number do not match in that case user input is compared with the random generated number.
  • Comparision displays the hint for the player. Entered number is greater or smaller than answer.

Source Code:

Here is the complete source code for the python number guessing game code.

import random

num = random.randint(0, 10)
print(f'''
---------------------------
Correct answer: {num}
---------------------------
''')

attempt = 4
msg = ''
while attempt > 0:
   
    user_input = int(input('Enter Number: '))
    if user_input == num:
        msg = 'You Won!'
        break
    elif user_input > num:
        print(f'{user_input} is greater.\nRemaining attempts: {attempt}.')
        attempt -= 1
        

    elif user_input < num:
        print(f'{user_input} is smaller.\nRemaining attempts: {attempt}.')
        attempt -= 1

    else:
        print('Something went wrong!')
        break
    
print(msg)

Output:

In this output, the program is generating a random number and the user is trying to guess it. There are a limited number of attempts. Player get hint on every incorrect answer.

python number guessing game code
Python Number Guessing Game Code

Read Python Dictionary Methods

Number Guessing Game Python Tkinter

In this section, we will learn to create a number guessing game using python Tkinter.

  • Python Tkinter is a module using which we can create GUI (Graphical User Interface) applications.
  • ws = Tk(), we have created an object of Tk class. Now we will mimic the class using ws object.
  • def check_guess() w have created this function wherein using if-else condition we have make sure that player still have chances available.
  • If chance is greater than 0 than comparision between user input and generated random number is performed.
  • Player will receive hint if entered incorrect number also there are only 5 chances.
from tkinter import *
import random

ws = Tk()
ws.title('PythonGuides')
ws.geometry('600x400')
ws.config(bg='#5671A6')

ranNum = random.randint(0, 10)
chance = 5
var = IntVar()
disp = StringVar()

def check_guess():
    global ranNum
    global chance
    usr_ip = var.get()
    if chance > 0:
        if usr_ip == ranNum:
            msg = f'You won! {ranNum} is the right answer.'
        elif usr_ip > ranNum:
            chance -= 1
            msg = f'{usr_ip} is greater. You have {chance} attempt left.'
        elif usr_ip < ranNum:
            chance -= 1
            msg = f'{usr_ip} is smaller. You have {chance} attempt left.'
        else:
            msg = 'Something went wrong!'
    else:
        msg = f'You Lost! you have {chance} attempt left.'

    disp.set(msg)


Label(
    ws,
    text='Number Guessing Game',
    font=('sans-serif', 20),
    relief=SOLID,
    padx=10,
    pady=10,
    bg='#F27D16'
).pack(pady=(10, 0))

Entry(
    ws,
    textvariable=var,
    font=('sans-serif', 18)
).pack(pady=(50, 10))

Button(
    ws,
    text='Submit Guess',
    font=('sans-serif', 18),
    command=check_guess
).pack()

Label(
    ws,
    textvariable=disp,
    bg='#5671A6',
    font=('sans-serif', 14)
).pack(pady=(20,0))


ws.mainloop()

Output:

In this output, the python number guessing game GUI is displayed. The Player will enter any number in the entry box and if that number matches the system-generated random number then the player wins the game.

python number guessing game using tkinter gui
Python Number Guessing Game GUI

Read 11 Python list methods

Number Guessing Game Python Project

In this section, we will create a number guessing game python project that you can use in your minor or major.

  • In this game we have created 4 pages:
    • Menu page
    • Start Game
    • Instructions
    • Settings
    • Quit Game
  • Clicking on the start button will take you to the main game page. Where you can play this game.
  • Quit Game button on the menu page will terminate the game.
  • Instructions and Settings are the todo page. You can write your own instructions and determine settings.
  • Settings could be related to changing the upper bound and lower bound range of the random number, changing theme of page (background color and foreground color), add sliders to turn on or off.
  • This way you can prepare a minor or major project that will help you in getting good grades.

Source code of the Menu Page:

from tkinter import *

def game():
    ws.destroy()
    import app

def instr():
    ws.destroy()
    import instruction

def change_setting():
    ws.destroy()
    import chng_setting


ws = Tk()
ws.title('PythonGuides')
ws.geometry('600x500')
ws.config(bg='#0D0D0D')

start_game = Button(
    ws,
    width=20,
    text='Start Game',
    font=('sans-serif', 14),
    bg='#8C3232',
    fg='white',
    command= game
)
start_game.place(x=160, y=120)

instructions = Button(
    ws,
    width=20,
    text='Instructions',
    font=('sans-serif', 14),
    bg='#8C3232',
    fg='white',
    command=instr
)
instructions.place(x=160, y=170)


setting = Button(
    ws,
    width=20,
    text='Settings',
    font=('sans-serif', 14),
    bg='#8C3232',
    fg='white',
    command=change_setting
)
setting.place(x=160, y=220)


exit = Button(
    ws,
    width=20,
    text='Quit Game',
    font=('sans-serif', 14),
    bg='#8C3232',
    fg='white',
    command=exit
)
exit.place(x=160, y=270)


ws.mainloop()

The output of the Menu Page:

Here is the output of the menu or main page of the application. Clicking on any other button will take you to the next page.

python number guessing game using tkinter menu
Python Number Guessing Game Using Tkinter Menu Page

Source code of the Start Game page:

Here is the source code of the complete Python project for the number guessing game. This game is GUI-based created using the python Tkinter library.

from tkinter import *
import random

ws = Tk()
ws.title('PythonGuides')
ws.geometry('600x400')
ws.config(bg='#5671A6')

ranNum = random.randint(0, 10)
chance = 5
var = IntVar()
disp = StringVar()

def check_guess():
    global ranNum
    global chance
    usr_ip = var.get()
    if chance > 0:
        if usr_ip == ranNum:
            msg = f'You won! {ranNum} is the right answer.'
        elif usr_ip > ranNum:
            chance -= 1
            msg = f'{usr_ip} is greater. You have {chance} attempt left.'
        elif usr_ip < ranNum:
            chance -= 1
            msg = f'{usr_ip} is smaller. You have {chance} attempt left.'
        else:
            msg = 'Something went wrong!'
    else:
        msg = f'You Lost! you have {chance} attempt left.'

    disp.set(msg)


Label(
    ws,
    text='Number Guessing Game',
    font=('sans-serif', 20),
    relief=SOLID,
    padx=10,
    pady=10,
    bg='#F27D16'
).pack(pady=(10, 0))

Entry(
    ws,
    textvariable=var,
    font=('sans-serif', 18)
).pack(pady=(50, 10))

Button(
    ws,
    text='Submit Guess',
    font=('sans-serif', 18),
    command=check_guess
).pack()

Label(
    ws,
    textvariable=disp,
    bg='#5671A6',
    font=('sans-serif', 14)
).pack(pady=(20,0))

ws.mainloop()

The output of the Start Game page:

In this output, the player has to enter the number and if that number matches with the system-generated random number then the player wins. The player is provided with 5 chances to guess the right number.

python tkinter number guessing game
Python Number Guessing Game GUI

You may like the following Python tutorials:

In this Python tutorial, we have learned how to create Python Number Guessing Game. Also, we have covered these topics.

  • Python Number Guessing Game Overview
  • Python Number Guessing Game While Loop
  • Python Number Guessing Game For Loop
  • Python Random Number Guessing Game
  • Python Number Guessing Game Code
  • Number Guessing Game Python Tkinter
  • Number Guessing Game Python Project