Guess the Number Project
In this project, we will build a simple game where the user has to guess a randomly generated number.
The goal is to bring together everything you have learned so far: variables, conditionals, loops, and functions.
What we are building
The program will:
- generate a random number
- ask the user to guess the number
- tell the user if the guess is too high or too low
- repeat until the user guesses correctly
At the end, we will also build a simple graphical interface using Tkinter.
Step 1: Generate a random number
First, we need to generate a random number.
import random
number = random.randint(1, 100)
This creates a random number between 1 and 100.
Step 2: Get user input
Now we ask the user for a guess:
guess = int(input("Enter your guess: "))
We convert the input to an integer using int().
Step 3: Compare the guess
We use conditionals to compare the guess with the number:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Correct")
Step 4: Repeat using a loop
We want the user to keep guessing until they find the correct number.
while guess != number:
guess = int(input("Enter your guess: "))
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
print("Correct")
Step 5: Organizing with functions
We can improve the structure by using functions:
import random
def get_random_number():
return random.randint(1, 100)
def check_guess(guess, number):
if guess < number:
return "Too low"
elif guess > number:
return "Too high"
else:
return "Correct"
def play_game():
number = get_random_number()
guess = None
while guess != number:
guess = int(input("Enter your guess: "))
result = check_guess(guess, number)
print(result)
play_game()
Step 6: Simple UI with Tkinter
Now we will build a simple graphical interface.
import random
import tkinter as tk
number = random.randint(1, 100)
def check():
guess = int(entry.get())
if guess < number:
label.config(text="Too low")
elif guess > number:
label.config(text="Too high")
else:
label.config(text="Correct")
root = tk.Tk()
root.title("Guess the Number")
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text="Check", command=check)
button.pack()
label = tk.Label(root, text="Enter a number")
label.pack()
root.mainloop()
This creates a basic window where the user can input a number and receive feedback.
The end!
Congrats for building the final project. You have now mastered the basics of Python and succesfully understood the basic concepts in programming :)
You can improve your project further by:
- adding a limited number of attempts
- displaying the number of tries
- adding a restart button in the UI
You can always check the documentation of tkinter for more details on how to use it!