Python: From Beginners to Pro (Project Part)

Python: From Beginners to Pro (Project Part)

In this section, we will take everything we have learned so far on Python and use what we have learned to create a tiny project we can push to Github to boost our resume. If you do not know how to use Github, I have written a detailed article on how to get started.

Our project today would be to create a GUI (Graphical User Interface) that allows users to guess numbers, and the more they guess, the more it shows them if they are too high or too low.

This project covers everything we have done so far, and if you have not checked it out, go read our previous article here, here, and here.

Verifying the Installation

Open your command prompt or terminal and type.

python --version

This should display the installed Python version.

User-uploaded image: s_431BCE3BEF1B6D1B4DF2322128112F71A7B195F87DC644288F7BF3C98A8B05E6_1718897557596_Screenshot+2024-06-20+at+16.32.23.png

Setting Up

First, we need to tell Python what tools we’re going to use.

import tkinter as tk
import random

These lines bring the tkinter library for our graphics and the random library to create mystery numbers.

Creating the Game Window

Now, let’s make the window where our game will live.

window = tk.Tk()
window.title("Guess the Number!")
window.geometry("300x200")

This creates a window using the tk.Tk() library tk and function Tk() gives it a title called Guess the Number and then the size of the windows, which we set as 300*200.

If you run this code, you will get a loop as it won’t open the GUI but rather be left in a loop.

We must close our endless loop by adding a window.mainloop()

Adding Game Elements

Let’s populate some things to our window.

label = tk.Label(window, text="Guess a number between 1 and 100:")
label.pack()

entry = tk.Entry(window)
entry.pack()

result_label = tk.Label(window, text="")
result_label.pack()

submit_button = tk.Button(window, text="Submit")
submit_button.pack()

new_game_button = tk.Button(window, text="New Game")
new_game_button.pack()

Each line adds something to our window: instructions, a place to type your guess, a spot for results, and buttons to submit your guess or start a new game.

label = tk.Label(window, text="Guess a number between 1 and 10:")
label.pack()

This Creates a label widget with text (Guess a number between 1 and 20) and add it to the window

entry = tk.Entry(window)
entry.pack()

This creates an entry widget for user input value and adds it to the window.

result_label = tk.Label(window, text="")
result_label.pack()

This creates a label widget to display results and add them to the window.

submit_button = tk.Button(window, text="Submit")
submit_button.pack()

Here, we created a submit button and added it to the window.

new_game_button = tk.Button(window, text="New Game")
new_game_button.pack()

Finally, we created a new game button and added it to the window.

Game Logic

Without the logic, we would have a GUI, but nothing would work, and that is not the focus, so let’s develop the logic based on what we have been learning so far

We would add the following code.

secret_number = random.randint(1, 10)
attempts = 0

def check_guess():
    global attempts
    guess = int(entry.get())
    attempts += 1

    if guess < secret_number:
        result_label.config(text="Too low! Try again.")
    elif guess > secret_number:
        result_label.config(text="Too high! Try again.")
    else:
        result_label.config(text=f"You got it in {attempts} attempts!")

def new_game():
    global secret_number, attempts
    secret_number = random.randint(1, 100)
    attempts = 0
    result_label.config(text="")
    entry.delete(0, tk.END)

submit_button.config(command=check_guess)
new_game_button.config(command=new_game)



secret_number = random.randint(1, 10)
attempts = 0

This initializes the game.
secret_number is set to a random integer between 1 and 10 using random.randint().
attempts is set to 0 to keep track of how many guesses the player makes.

Reason: We use random.randint() to create unpredictability in the game. Starting attempts at 0 allows us to count from the first guess.

Alternative: We could use random.choice(range(1, 11)) instead, but randint is more straightforward for beginners.

def check_guess():
    global attempts
    guess = int(entry.get())
    attempts += 1

This function is called when the player submits a guess.
global attempts allows us to modify the attempts variable that was defined outside the function.

int(entry.get()) converts the player’s input from a string to an integer.

attempts is incremented by 1 for each guess.

Reason: We use global because attempts is defined outside the function. We convert the input to an integer because entry.get() returns a string, but we need a number for comparison.

Alternative: Instead of using a global variable, we could pass attempts as an argument and return its new value, but this is more complex for beginners.

    if guess < secret_number:
        result_label.config(text="Too low! Try again.")
    elif guess > secret_number:
        result_label.config(text="Too high! Try again.")
    else:
        result_label.config(text=f"You got it in {attempts} attempts!")

This checks the player’s guess against the secret number and updates the result label accordingly.
Reason: We use if-elif-else structure for clarity. The config() method updates the text of the label widget.

We could use a match-case statement in Python 3.10+, but if-elif-else is more widely understood, we discussed it above.

def new_game():
    global secret_number, attempts
    secret_number = random.randint(1, 100)
    attempts = 0
    result_label.config(text="")
    entry.delete(0, tk.END)

This function resets the game state.

  • It generates a new secret number and resets attempts to 0.
  • It clears the result label and the entry widget.

We need to reset all game state variables and clear the UI for a fresh start.

submit_button.config(command=check_guess)
new_game_button.config(command=new_game)

This connects the button clicks to their respective functions.

The best way for beginners to grasp this

  • Understand the game flow: initialization, guessing, and resetting.
  • Focus on how variables (secret_number, attempts) are used to maintain game state.
  • Notice how functions (check_guess, new_game) encapsulate specific behaviors.
  • Observe how the UI elements (labels, entry, buttons) are updated to reflect the game state.
  • Experiment by modifying values (e.g., change the range of random numbers) to see how it affects the game.

Run the Game

Finally, let’s start the game

You can find the complete code here.

Conclusion

Congratulations! You’ve just created your very own Number Guessing Game with a graphical interface.

  1. How to create a window for your game
  2. Adding labels, buttons, and entry fields to your window
  3. Creating game logic to check guesses
  4. Using functions to make your buttons work

Remember, the most important part is understanding each step. Don’t worry if your game doesn’t work perfectly right away. Keep practicing and experimenting with your code.

In the next episode we will turn our application into an app we can send to our phone.

If you like my work and want to help me continue dropping content like this, buy me a cup of coffee.

If you find our post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.

Resource

Leave a Comment

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