Python Level 7: Mini Project – Number Guessing Game

Goal for Today

Today you will apply everything you have learned in a small project:

By the end, you will have a fully working guessing game that reacts to user input.

Step 1: Generate a Random Number

Python can generate random numbers using the random module.

import random → include the module

random.randint(1, 10) → number between 1 and 10


import random

number = random.randint(1, 10)

Now Python knows: number is a random number between 1 and 10.

Step 2: User Input in a Loop

We want the game to continue until the player guesses correctly.

For that, we use a while loop.


guess = 0  # starting value

while guess != number:
    guess = int(input("Guess the number from 1 to 10: "))

Explanation:

Step 3: Check Conditions

We give hints:


if guess < number:
    print("Too low!")
elif guess > number:
    print("Too high!")
else:
    print("Correct!")

Step 4: Put Everything Together


import random

number = random.randint(1, 10)
guess = 0

while guess != number:
    guess = int(input("Guess the number from 1 to 10: "))
    if guess < number:
        print("Too low!")
    elif guess > number:
        print("Too high!")
    else:
        print("Correct!")

Step 5: Bonus Task – Count Attempts

We want to know how many attempts the player needed.

Start attempt counter: attempts = 0

Increase with each guess: attempts = attempts + 1

Print at the end: print("You needed X attempts")


import random

number = random.randint(1, 10)
guess = 0
attempts = 0

while guess != number:
    guess = int(input("Guess the number from 1 to 10: "))
    attempts = attempts + 1
    if guess < number:
        print("Too low!")
    elif guess > number:
        print("Too high!")
    else:
        print("Correct! You needed", attempts, "attempts!")

This small project demonstrates: