Python Number Guessing Game Project with Source Code

Get Job-ready with hands-on learning & real-time projects - Enroll Now!

Everybody loves playing games. Number games are so much fun and also so good for brain activities. In this project, we are going to create a fun Number Guessing game using python. Let us start making the project.

About Number Guessing Game Project

Today we are going to create a Number Guessing Game. This game is about creating an interactive game that will display scores and a person has to guess the number. There will be hints displayed every time the user guesses a wrong number. The objective of creating this project is to challenge our brains and add some fun while learning python.

Python Number Guessing Game Project Details

During the creation of the project, we are going to use two libraries-

1. Tkinter – Tkinter Module will help us create an easy GUI in python with lots of inbuilt functions that we will learn.

2. Random – We will use the Random Module to generate a random number that the user will be guessing. This number will only be known to the computer.

Project Prerequisites

To create this project we need to install the two libraries that we will be using for creation of the project. The commands are given below.

1. Tkinter –

pip install tk

2. Random –

pip install random

Download the Source Code for Number Guessing Game using Python

Before proceeding with the project, please download the source code of python number guessing game project: Python Number Guessing Game Code

Steps To Create Python Number Guessing Game Project

Below given are the steps to create the python Number Guessing Game:

  1. Import the required libraries
  2. Creating the GUI window
  3. Creating the Labels, Entry boxes and Buttons
  4. Create the Main Function – Execution of the game.

1. Importing the Required Libraries for Python Number Guessing Game

import tkinter as tk
from tkinter import *
import random
  • Tkinter Module – Tkinter Module will provide us with a lot of inbuilt functions that will help us with the creation of a GUI window.
  • Random Module – We will be using this module to generate a random number that the user will be guessing. Generating a random number will make the game very interesting and exciting.

2. Creating the GUI Window:

win = tk.Tk()
win.geometry("750x750")
win.title("PythonGeeks")
  • Using the TK() we make a window named win.
  • We specify the size of the window using the geometry() function and give a title to it using the title() function. Both these functions are a part of the Tkinter Module.

3. Creating the Labels, Entry Boxes and Button:

 
Entry(win, textvariable=guess, width=3,font=('Ubuntu', 50), relief=GROOVE).place(relx=0.5, rely=0.3, anchor=CENTER)
 
Entry(win, textvariable=hint, width=50,font=('Courier', 15), relief=GROOVE,bg='orange').place(relx=0.5, rely=0.7, anchor=CENTER)
 
Entry(win, text=final_score, width=2,font=('Ubuntu', 24), relief=GROOVE).place(relx=0.61, rely=0.85, anchor=CENTER)
 
Label(win, text='I challenge you to guess the number ',font=("Courier", 25)).place(relx=0.5, rely=0.09, anchor=CENTER)
 
Label(win, text='Score out of 5',font=("Courier", 25)).place(relx=0.3, rely=0.85, anchor=CENTER)
 
Button(win, width=8, text='CHECK', font=('Courier', 25), command=fun, relief=GROOVE,bg='light blue').place(relx=0.5, rely=0.5, anchor=CENTER)
  • As visible in the output, we have created an entry field using the Entry() function where we specify the width of the entry field, font, size of the text etc. To place this entry field, we make use of the place() function. In the place() function, we specify the x-y coordinates and also the anchor as center. There are a total of 3 Entry fields that we have created. They are-
    1. Entry area to enter a number.
    2. Displaying the current score.
    3. Displaying the hints.
  • We have created labels using the Label() function. These labels are primarily to display a text.To place this label, we make use of the place() function. In the place() function, we specify the x-y coordinates and also the anchor as center.
  • We create a Check Button which will check if the user’s number is equal to the number generated through the random module. command=fun will initiate the fun function which will generate hints and perform the comparison between the generated number and the number entered by the user.

4. Create The Main Function – Execution of the game:

num=random.randint(1,50)
  • Randint() – this function is to randomly generate a number in the specified range(here the range is 1-50). We have created a num variable and store the randomly generated number in this variable.
hint = StringVar()
score = IntVar()
final_score= IntVar()
guess= IntVar()
  • Hint- For displaying the hints. Using the StringVar() method we have specified that it is of string type.
  • Score – For displaying the score initially. Using the IntVar() method we have specified that it is of integer type.
  • Final_score – For displaying the updated score after every round or every guess. Using the IntVar() method we have specified that it is of integer type.
  • Guess – This stores the number that the user has entered.
hint.set("Guess a number between 1 to 50 ")
score.set(5)
final_score.set(score.get())

Using the set() method we set what will be the value of these variables when they are displayed on the window.

def fun():
    x=guess.get()
    final_score.set(score.get())
    if score.get()>0:
 
        if x > 20 or x<0:
            hint.set("You just lost 1 Chance")
            score.set(score.get()-1)
            final_score.set(score.get())
   
        elif num==x:
            hint.set("Congratulation YOU WON!!!")
            score.set(score.get()-1)
            final_score.set(score.get())
     
        elif num > x:
            hint.set("Your guess was too low: Guess a number higher ")
            score.set(score.get()-1)
            final_score.set(score.get())
        elif num < x:
            hint.set("Your guess was too High: Guess a number Lower ")
            score.set(score.get()-1)
            final_score.set(score.get())
    else:
         hint.set("Game Over You Lost")
  • We have created a function fun() to compare the number entered to the generated number and then after comparing make the necessary changes on the display window.
  • We have extracted the entered number using the get() method and saved its value in a variable x.
  • Using the if-else loops in python, we check if the number is equal to the generated number, less than, greater than or not in the range. According to these conditions we update the score and hints. Everytime a guess goes wrong the final score becomes one less so there are a total of 5 chances.
  • If the user guesses the right number, a congratulatory message is displayed. If a user loses all chances then a sorry message is displayed. We set the value of these variables as given in the conditions using the set() method.

Hurray! We have created the game successfully. Now let us play the games and have a look.

Python Number Guessing Game Output

This is how the window looks when opened. Let’s guess a random number.

Oh! we lost a chance. Look at the hint and repeat the process till you win or lose.

Oh no! We lost the game. Now you make the game and try if you can challenge your brain with this fun game.

python number guessing game output

Summary

We have successfully created the Number Guessing Game with the help of Tkinter Module and Random Module of Python. We learned about these modules and their inbuilt functions during the project.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


PythonGeeks Team

At PythonGeeks, our team provides comprehensive guides on Python programming, AI, Data Science, and machine learning. We are passionate about simplifying Python for coders of all levels, offering career-focused resources.

10 Responses

  1. Dennis says:

    Thnx for helping me

  2. Gagan Dinesh says:

    After running the program we find the error the The word “guess” is not defined in the code i tried all the way possible can u correct me with the issue

  3. E.A89 says:

    me too, i couldn’t fix it

  4. Randomperson :) says:

    me too

  5. Indrajit Prasad says:

    use single quote
    as ‘guess’

  6. fathima hana says:

    its showing some thing is wrong with the module or smth.
    iam a beginner and have literally no idea ab this so iam very confused

  7. viper75 says:

    The problem with this code is that the line numbers for each snippet begin with 1. You need to declare/initialize the variables first, before you can use them. Try to think about the order of operations, basically from top to the bottom. In order for the window (win in this case) to use the declared functions, the functions must be available before the window is instantiated/created.

  8. viper75 says:

    Also, please do not use SMS texting lingo/abbreviations. It makes reading your comments more difficult for people who are not familiar with the shorthand. If the tutorials on this site are too confusing, try watching a YT tutorial first, then go through these tutorials. Having someone walk through the first time, assuming they do it well, will definitely help you understand how to put this code together.

  9. viper75 says:

    I was wrong about when to declare the variables. I was not familiar enough with how tkinter worked.
    0. Import modules
    1. declare the function
    2. create the screen/form
    3. declare variables
    4. be sure to include the Screen.update() and .mainLoop() at the end of your code, to run the code!

    I was attempting to use the a main() function to encapsulate the Screen and variable declarations, but the .get/set() methods did not work and if the variables were declared before the control function, I got the message that it is too early to declare variables.

  10. Prashant Bangera says:

    import tkinter as tk
    import random

    win = tk.Tk()
    win.geometry(“750×750”)
    win.title(“Number Guessing Game”)

    # Variables
    hint = tk.StringVar()
    score = tk.IntVar()
    final_score = tk.IntVar()
    guess = tk.IntVar()
    difficulty = tk.StringVar(value=”Medium”)
    num = random.randint(1, 50)
    timer = None
    time_left = tk.IntVar()

    # Set initial score based on difficulty
    def set_difficulty():
    level = difficulty.get()
    if level == “Easy”:
    score.set(10)
    elif level == “Hard”:
    score.set(3)
    else:
    score.set(5)
    final_score.set(score.get())
    time_left.set(10)

    # Countdown Timer
    def countdown():
    global timer
    if time_left.get() > 0:
    time_left.set(time_left.get() – 1)
    timer = win.after(1000, countdown)
    else:
    # Time’s up
    score.set(score.get() – 1)
    final_score.set(score.get())
    hint.set(“⏰ Time’s up! You lost 1 chance.”)
    if score.get() == 0:
    hint.set(f”Game Over. You lost. The number was {num}.”)

    # Check guess
    def fun():
    global timer
    win.after_cancel(timer) # Stop current timer
    x = guess.get()
    if score.get() > 0:
    if num == x:
    hint.set(“🎉 Congratulations! YOU WON!!! 🎉”)
    final_score.set(score.get())
    score.set(0)
    elif num > x:
    hint.set(“Too low. Try a higher number.”)
    score.set(score.get() – 1)
    elif num < x:
    hint.set("Too high. Try a lower number.")
    score.set(score.get() – 1)

    final_score.set(score.get())

    if score.get() == 0 and num != x:
    hint.set(f"Game Over. You lost. The number was {num}.")
    else:
    time_left.set(10)
    countdown()
    else:
    hint.set(f"Game Over. You lost. The number was {num}.")

    # Reset the game
    def reset_game():
    global num, timer
    if timer:
    win.after_cancel(timer)
    num = random.randint(1, 50)
    guess.set(1)
    hint.set("")
    set_difficulty()
    time_left.set(10)
    countdown()

    # UI Elements
    tk.Label(win, text='I challenge you to guess the number ', font=("Courier", 25)).place(relx=0.5, rely=0.07, anchor=tk.CENTER)

    # Difficulty menu
    tk.Label(win, text='Select Difficulty:', font=("Courier", 16)).place(relx=0.25, rely=0.15, anchor=tk.CENTER)
    tk.OptionMenu(win, difficulty, "Easy", "Medium", "Hard").place(relx=0.45, rely=0.15, anchor=tk.CENTER)

    # Guess input using Spinbox
    tk.Spinbox(win, from_=1, to=50, textvariable=guess, width=3, font=('Ubuntu', 50), relief=tk.GROOVE).place(relx=0.5, rely=0.3, anchor=tk.CENTER)

    # Hint area
    tk.Entry(win, textvariable=hint, width=50, font=('Courier', 15), relief=tk.GROOVE, bg='orange').place(relx=0.5, rely=0.7, anchor=tk.CENTER)

    # Score display
    tk.Label(win, text='Score out of:', font=("Courier", 20)).place(relx=0.25, rely=0.85, anchor=tk.CENTER)
    tk.Entry(win, textvariable=final_score, width=2, font=('Ubuntu', 24), relief=tk.GROOVE).place(relx=0.5, rely=0.85, anchor=tk.CENTER)

    # Timer display
    tk.Label(win, text='⏱ Time left:', font=("Courier", 20)).place(relx=0.25, rely=0.78, anchor=tk.CENTER)
    tk.Entry(win, textvariable=time_left, width=2, font=('Ubuntu', 24), relief=tk.GROOVE).place(relx=0.5, rely=0.78, anchor=tk.CENTER)

    # Buttons
    tk.Button(win, width=8, text='CHECK', font=('Courier', 25), command=fun, relief=tk.GROOVE, bg='light blue').place(relx=0.5, rely=0.5, anchor=tk.CENTER)
    tk.Button(win, width=10, text='PLAY AGAIN', font=('Courier', 18), command=reset_game, relief=tk.GROOVE, bg='light green').place(relx=0.5, rely=0.95, anchor=tk.CENTER)

    # Start game initially
    reset_game()
    win.mainloop()

Leave a Reply

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