Building small projects is one of the best ways to master programming. Among them, the Number Guessing Game Using Python stands out as a beginner‑friendly project that introduces you to random number generation, loops, conditionals, and user interaction in the command line interface (CLI). In this article, we will walk through every detail of creating this project, understand its logic, explore the code, and even test the output to see it in action.
Problem Statement
The task is simple yet engaging: create a CLI game where the program randomly selects a number between 1 and 100, and the user has to guess it. The user will get a limited number of attempts, and the program will guide them by giving hints — whether their guess is too high or too low. If the user guesses correctly, the game ends with a congratulatory message. If not, the game reveals the number after all attempts are used.
What You Will Learn
By building this project, you will strengthen the following programming concepts:
- Using the
random
module to generate random numbers. - Conditional logic with
if
,elif
, andelse
. - Loops and user input handling for repeated guesses.
- Feedback system in games to keep users engaged.
These concepts are not only useful for games but also form the foundation of larger real‑world applications.
Step‑by‑Step Development
Let’s break down the process of developing this project:
1. Import the Random Module
Python’s built‑in random
module allows us to generate random numbers. We use random.randint(1, 100)
to pick a number between 1 and 100.
import random
number = random.randint(1, 100)
This line ensures the game picks a secret number before the user starts guessing.
2. Define Attempts
To make the game more interesting, we restrict the number of guesses. For example, we can set a maximum of 7 attempts.
attempts = 0
max_attempts = 7
This adds a challenge element — the player cannot just try unlimited numbers.
3. Display Game Instructions
It’s always good to let the player know what to expect.
print("🎲 Guess the Number (1 to 100)")
4. Use a Loop for Repeated Guesses
We want the game to continue until either:
- The user guesses the number correctly, or
- The user runs out of attempts.
For this, we use a while
loop:
while attempts < max_attempts:
# ask for input
# check the guess
5. Accept User Input
We use the input()
function to read the player’s guess. Since input is a string, we convert it into an integer with int()
.
guess = int(input(f"Attempt {attempts+1}: Enter your guess: "))
The f
string helps format the message to show the current attempt number.
6. Compare Guess with the Secret Number
Now comes the core logic:
if guess == number:
print("🎉 Correct! You guessed it.")
break
elif guess < number:
print("📉 Too low!")
else:
print("📈 Too high!")
- If the guess equals the number → Success!
- If the guess is smaller → Show hint: “Too low!”
- If the guess is larger → Show hint: “Too high!”
7. Handle Errors Gracefully
What if the user types text instead of a number? Without handling this, the program would crash. To prevent this, we use try...except
.
try:
guess = int(input(...))
except ValueError:
print("❌ Please enter a valid number.")
8. Ending the Game
If the user does not guess correctly within the allowed attempts, we reveal the number:
if attempts == max_attempts and guess != number:
print(f"😢 Out of attempts! The number was {number}.")
Complete Source Code
Here’s the complete implementation:
import random
number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("🎲 Guess the Number (1 to 100)")
while attempts < max_attempts:
try:
guess = int(input(f"Attempt {attempts+1}: Enter your guess: "))
attempts += 1
if guess == number:
print("🎉 Correct! You guessed it.")
break
elif guess < number:
print("📉 Too low!")
else:
print("📈 Too high!")
except ValueError:
print("❌ Please enter a valid number.")
if attempts == max_attempts and guess != number:
print(f"😢 Out of attempts! The number was {number}.")
Sample Interaction
Here’s how the game looks when played:
🎲 Guess the Number (1 to 100)
Attempt 1: Enter your guess: 45
📉 Too low!
Attempt 2: Enter your guess: 75
📈 Too high!
Attempt 3: Enter your guess: 60
📉 Too low!
Attempt 4: Enter your guess: 68
🎉 Correct! You guessed it.
This interaction shows how the player gets hints after each attempt, making the game fun and engaging.
How the Game Works Internally
To appreciate the simplicity of this project, let’s break it down logically:
- A secret number is generated at the beginning.
- The user is allowed a fixed number of attempts.
- Each guess is compared with the secret number.
- Feedback is provided immediately.
- If guessed correctly → game ends.
- If attempts finish without a correct guess → reveal the number.
This simple cycle is a foundation for building more advanced games in Python.
Possible Enhancements
While this project is complete as it is, you can always make improvements:
- Difficulty Levels: Easy (10 attempts), Medium (7 attempts), Hard (5 attempts).
- Range Customization: Allow the user to set the guessing range.
- Score System: Award points based on attempts left.
- Replay Option: Ask if the player wants to play again.
- Hints System: Provide special hints after 3 wrong attempts.
Adding these features will not only make the game more enjoyable but also help you practice more advanced coding techniques.
Why This Project is Important
This project may look simple, but it covers essential Python topics:
- Randomization (important in games, simulations, and AI).
- Loops and conditions (used in almost every project).
- User input handling (vital for interactive applications).
- Error handling (ensures programs do not crash unexpectedly).
Once you are comfortable with this project, you’ll find it much easier to transition into more complex applications.
By experimenting with variations of this game, you’ll not only sharpen your coding skills but also gain confidence in writing interactive programs. This confidence becomes the stepping stone for building larger, real‑world applications.
Python Projects: