Skip to main content

Classic Number Guessing Game Using Python

 

 


Build Your First Python Game: The Classic Number Guessing Game!

Are you learning Python and looking for a fun, hands-on project to test your skills? You’ve come to the right place.

When starting out with programming, it’s easy to get stuck just reading tutorials. The real magic happens when you build something interactive.

Today, we’re going to build a classic: The Number Guessing Game.

It’s simple concept: The computer picks a random number between 1 and 100, and you have a limited number of tries to guess it. After every guess, the computer tells you if you need to go "Higher" or "Lower."

Why This is the Perfect Beginner Project

Despite its simplicity, this game is a fantastic learning tool because it combines several fundamental programming concepts into one cohesive package.

By building this, you will master:

  • Variables: Storing information like the secret number and attempts left.

  • Loops (while): Keeping the game running until the player wins or loses.

  • Conditionals (if/elif/else): Making decisions based on the user's guess.

  • Input handling: Getting data from the user and converting it into usable numbers.

  • Error Handling (try/except): A crucial skill—making sure your program doesn't crash if the user types "banana" instead of a number!

Let's dive into the code.


The Full Python Code

Here is the complete script for the game. You can copy this code, save it in a text editor as guessing_game.py, and run it.

Python Code
import random

def number_guessing_game():
    # --- Configuration ---
    # Define the range for the random number
    lower_bound = 1
    upper_bound = 100
    # Define the maximum number of attempts
    max_attempts = 10

    # --- Game Setup ---
    # Generate a random number between lower_bound and upper_bound (inclusive)
    secret_number = random.randint(lower_bound, upper_bound)
    attempts_left = max_attempts
    
    print("Let's play the Number Guessing Game!")
    print(f"I'm thinking of a number between {lower_bound} and {upper_bound}.")
    print(f"You have {max_attempts} attempts to guess it.")
    
    # --- Main Game Loop ---
    while attempts_left > 0:
        print(f"\nAttempts left: {attempts_left}")
        
        # Get user input and handle potential errors
        try:
            # We try to convert the input into an integer
            guess = int(input("Take a guess: "))
        except ValueError:
            # If the input wasn't a number, this block catches the error
            print("That's not a valid number. Please enter an integer.")
            # 'continue' jumps back to the start of the loop without counting the attempt
            continue
            
        # Check if the guess is within the valid range (optional but good practice)
        if guess < lower_bound or guess > upper_bound:
            print(f"Your guess is outside the range ({lower_bound} to {upper_bound}). Try again.")
            continue

        # --- The Logic Check ---
        if guess == secret_number:
            # User wins!
            attempts_used = max_attempts - attempts_left + 1
            print(f"\nšŸŽ‰ **CONGRATULATIONS!** šŸŽ‰")
            print(f"You guessed the number {secret_number} correctly in {attempts_used} attempts.")
            # 'return' ends the function immediately
            return 
        
        elif guess < secret_number:
            print("Too Low! Try a higher number.")
        
        else: # guess must be > secret_number
            print("Too High! Try a lower number.")
            
        # Decrease the attempt counter only for incorrect, valid guesses
        attempts_left -= 1
        
    # --- Game Over Condition ---
    # This part executes only if the loop finishes without a win
    print("\nšŸ’” **GAME OVER!** šŸ’”")
    print(f"You ran out of attempts. The secret number was **{secret_number}**.")

# Start the game by calling the function
if __name__ == "__main__":
    number_guessing_game()

How It Works: The Breakdown

Let's walk through the key parts of the code so you understand exactly what's happening.

1. Setting the Stage (Import and Config)

At the very top, we do import random. Python doesn't naturally know how to pick random numbers; this line imports a "module" that gives it that ability. We also set up variables at the start for the range (1-100) and the attempts (10). This makes it easy to change the game's difficulty later just by editing those two numbers.

2. Picking the Secret Number

secret_number = random.randint(lower_bound, upper_bound) This is where the magic happens. The computer picks an integer inclusive of the bounds we set and stores it secretly.

3. The Game Loop (while)

while attempts_left > 0: This is the heart of the game. As long as the player has more than zero attempts remaining, everything inside this block will repeat.

4. Handling User Input Safely (try/except)

This is a pro move for beginners. If we just used int(input(...)) and the user typed text (like "hello"), the program would crash with a ValueError. By wrapping it in a try... except ValueError block, we tell Python: "Try to convert this input to a number. If it fails, don't crash; just print a warning message and let them try again."

5. The Logic Check (if/elif/else)

Once we have a valid numbered guess, we compare it to the secret number:

  • IF it matches: Print a victory message and use return to exit the entire function immediately. Game over, you win!

  • ELIF (Else If) it's lower: Tell the user to guess higher.

  • ELSE: It must be higher, so tell the user to guess lower.

6. The Game Over State

If the player uses up all 10 attempts, the while loop finishes. The code immediately following the loop is the "Game Over" section, which reveals the secret number.


Leveling Up: Challenge Ideas

Once you have this code running, don't stop there! The best way to learn is to modify existing code. Try adding these features:

  1. Difficulty Selection: At the start, ask the user if they want "Easy" (20 attempts), "Medium" (10 attempts), or "Hard" (5 attempts) mode.

  2. Play Again Loop: When the game ends, ask the user if they want to play another round without having to restart the program.

  3. Score Tracking: Try to keep track of the fewest attempts it took to win in a single session.

Happy coding!

Comments

Popular posts from this blog

Simple Number Guessing Game in Python

  Build a Simple Number Guessing Game in Python: A Beginner-Friendly Project Are you looking to dive into Python programming with a fun and interactive project? The number guessing game Python project is an excellent starting point for beginners. This classic game challenges players to guess a randomly generated number within a limited number of attempts, helping you practice essential concepts like loops, conditionals, and user input. In this blog post, we'll walk through how to create your own Python guessing game project , complete with code and detailed explanations. Whether you're a student, hobbyist, or aspiring developer, this tutorial will boost your skills while keeping things engaging. Why Choose a Number Guessing Game as Your Python Project? The number guessing game Python is one of the most searched beginner projects because it's simple yet versatile. It teaches core programming fundamentals without overwhelming you with complex libraries or frameworks. Her...

Python GUI Program to Calculate Age

Python GUI Program to Calculate Age     Certainly! Below is a Python program using the tkinter library to create a simple GUI that accepts a date of birth and calculates the age.   import tkinter as tk from tkinter import messagebox from datetime import datetime def calculate_age():     dob_str = entry_dob.get()     try:         dob = datetime.strptime(dob_str, "%Y-%m-%d")         today = datetime.today()         age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))         messagebox.showinfo("Age Calculator", f"Your age is: {age} years")     except ValueError:         messagebox.showerror("Error", "Please enter the date in YYYY-MM-DD format") # Create the main window root = tk.Tk() root.title("Age Calculator") # Create a labe...