PYTHON PROJECT 02

Number Guessing Game

Learn how to build a simple Number Guessing Game using Python variables, random numbers, loops, conditions, user input and comparison operators.

1. Project Introduction

A Number Guessing Game is a beginner-friendly Python project where the computer generates a random number and the player tries to guess it.

After every guess, the program tells the player whether the guessed number is too high, too low, or correct.

This project is useful for learning Python conditions, loops, random numbers and user input.

2. Importing the Random Module

Python provides a built-in module called random.

We can use it to generate a random number.

import random

3. Generating a Random Number

The randint() function generates a random integer between two numbers.

secret_number = random.randint(1, 100)

In this example, Python generates a number between 1 and 100.

4. Taking User Input

The input() function allows the player to enter a guess.

guess = input("Enter your guess: ")

Remember that input normally returns text. Therefore, we convert it into an integer.

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

5. Comparing the Guess

Now we compare the user's guess with the secret number.

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

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

else:
    print("Too high!")

6. Using a Loop

A single guess is not enough for a game. We want the player to continue guessing until the correct number is found.

A while loop is useful for this.

while guess != secret_number:
    guess = int(input("Guess again: "))

7. Counting Attempts

We can also count how many attempts the player needs.

attempts = 0

attempts += 1

Every time the player enters a guess, we increase the attempts variable.

8. Giving Hints

The game becomes more interactive when we provide hints.

if guess < secret_number:
    print("Try a higher number.")

elif guess > secret_number:
    print("Try a lower number.")

else:
    print("You guessed it!")

9. Adding Input Validation

Users may enter numbers outside the allowed range. We can check that the number is between 1 and 100.

if guess < 1 or guess > 100:
    print("Please enter a number between 1 and 100.")

10. Complete Project Flow

01 Import random
02 Generate number
03 Take guess
04 Compare values
05 Give hint
06 Count attempts
07 Repeat loop
08 Show result

11. Concepts You Practiced

12. Run Complete Project 🚀

You have now learned how the Number Guessing Game works. Open the complete project to see the working version.

Run Complete Project