Home → Projects → Number Guessing Game

Project 02: Number Guessing Game

Build a fun number guessing game using Python.

Beginner Python Project 02

📌 Project Overview

In this project, the computer chooses a random number and the player tries to guess it.

What you will learn:
  • Using Python's random module
  • Taking user input
  • Using if-elif-else
  • Using while loops
  • Counting attempts

🎯 Play the Number Guessing Game

I have selected a number between 1 and 100. Try to guess it!

Enter your first guess.
Attempts: 0

🎮 How the Game Works

1 Computer selects a number
2 Player enters a guess
3 Python checks the guess
4 Player gets a hint

Step 1: Import Random

Python provides the random module for generating random values.

Python
import random

Step 2: Generate a Number

Generate a random number between 1 and 100.

Python
secret_number = random.randint(1, 100)

Step 3: Get the Guess

Python
guess = int(input("Enter your guess: "))

Step 4: Check the Guess

Python
if guess == secret_number:
    print("Correct!")

elif guess < secret_number:
    print("Too low!")

else:
    print("Too high!")

🚀 Complete Python Code

number_guessing.py
import random

secret_number = random.randint(1, 100)

attempts = 0

print("===== Number Guessing Game =====")
print("Guess a number between 1 and 100.")

while True:

    guess = int(input("Enter your guess: "))

    attempts += 1

    if guess == secret_number:

        print("🎉 Correct!")
        print("You guessed it in", attempts, "attempts.")
        break

    elif guess < secret_number:

        print("Too low! Try again.")

    else:

        print("Too high! Try again.")

💻 Example Output

===== Number Guessing Game =====

Guess a number between 1 and 100.

Enter your guess: 40
Too low! Try again.

Enter your guess: 75
Too high! Try again.

Enter your guess: 62
🎉 Correct!

You guessed it in 3 attempts.

🧠 Mini Challenge

Improve the game by adding these features:

← Previous Project Next Project →