If you’re just starting out with Python and want a fun, quick project to test your skills — this one’s for you.
In this tutorial, we’ll guide you step-by-step to create a Number Guessing Game using Python. It’s simple, interactive, and helps you practice key concepts like:
- Variables
- Loops
- Conditional statements
- Random number generation
- User input
Let’s get coding! 💻
🧠 What Does the Game Do?
- The computer picks a random number between 1 and 100.
- You try to guess the number.
- It tells you if your guess is too high or too low.
- It keeps going until you guess correctly.
- At the end, it shows how many tries you took.
🧰 Tools You Need
You can run this code on:
- ✅ Replit (browser-based)
- ✅ Google Colab
- ✅ Python installed locally (with VS Code or IDLE)
🧾 Step-by-Step Python Code
✅ Full Code:
pythonCopyEditimport random
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
# Generate a random number
secret_number = random.randint(1, 100)
guesses = 0
while True:
try:
guess = int(input("Enter your guess: "))
guesses += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed it in {guesses} tries.")
break
except ValueError:
print("Please enter a valid number.")
🔍 Code Explained Line by Line
import random
This lets us generate random numbers.random.randint(1, 100)
Picks a random number between 1 and 100 (inclusive).while True:
This keeps the game running until the user guesses correctly.int(input(...))
Gets the user’s input and converts it to an integer.if,elif,else
Controls the game logic — tells user if the guess is too high, low, or correct.break
Exits the loop when the correct number is guessed.try/except
Catches input errors so the program doesn’t crash if the user types a letter.
🛠️ Ways to Customize the Game
- 🔁 Add difficulty levels (Easy: 1–50, Hard: 1–200)
- ⏱️ Add a timer
- 📊 Track high scores
- 🔊 Add sound using the
playsoundmodule - 🎨 Add graphics with
tkinter(advanced)
🎯 Final Thoughts
This game is a great introduction to real-world Python programming. It uses the core concepts of logic, user input, and randomness — all in less than 25 lines of code!
Practice tweaking the code, adding features, and challenging yourself to make it even better.
🔜 Coming Up Next:
“How to Build a To-Do List in Python (Console App)” ✅
