Kahibaro
Discord Login Register

Number guessing game

Overview

In this mini project, you’ll build a number guessing game in Python.

The idea:

This project practices:

You’ll see several versions, from simple to slightly more advanced.


Version 1: A Very Simple Guessing Game

This first version has:

# Very simple number guessing game
secret_number = 7  # you can change this
guess = int(input("Guess the number: "))
if guess == secret_number:
    print("Correct! You guessed the number.")
else:
    print("Sorry, that's not correct.")

This is not very fun yet: the user only gets one guess and the number never changes. Next, you’ll improve it.


Version 2: Random Secret Number and Unlimited Guesses

Now you’ll:

import random
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
secret_number = random.randint(1, 100)  # random number from 1 to 100
guesses_taken = 0
while True:
    guess_text = input("Take a guess: ")
    # Convert input to an integer
    guess = int(guess_text)
    guesses_taken = guesses_taken + 1
    if guess < secret_number:
        print("Too low! Try again.")
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print("Correct! You guessed the number.")
        print("You took", guesses_taken, "guesses.")
        break  # exit the loop when guessed correctly

Points to notice:

Handling Invalid Input

Right now, if the player types something that’s not a number (like hello), the program will crash. Let’s handle that more safely.

You can use try / except to catch errors when converting input to an int.

import random
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
secret_number = random.randint(1, 100)
guesses_taken = 0
while True:
    guess_text = input("Take a guess: ")
    # Try to convert input to a number
    try:
        guess = int(guess_text)
    except ValueError:
        print("That is not a valid number. Please enter a whole number.")
        continue  # go back to the top of the loop
    # Optional: check if the guess is in the valid range
    if guess < 1 or guess > 100:
        print("Please guess a number between 1 and 100.")
        continue
    guesses_taken = guesses_taken + 1
    if guess < secret_number:
        print("Too low! Try again.")
    elif guess > secret_number:
        print("Too high! Try again.")
    else:
        print("Correct! You guessed the number in", guesses_taken, "guesses.")
        break

Now:

Version 3: Limiting the Number of Attempts

To make the game more challenging, you can:

For example, allow 10 guesses:

import random
MAX_ATTEMPTS = 10  # use a constant to make it easy to change later
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("You have", MAX_ATTEMPTS, "attempts to guess it.")
secret_number = random.randint(1, 100)
guesses_taken = 0
while guesses_taken < MAX_ATTEMPTS:
    guess_text = input("Guess (" + str(MAX_ATTEMPTS - guesses_taken) + " attempts left): ")
    try:
        guess = int(guess_text)
    except ValueError:
        print("Please enter a valid whole number.")
        continue
    if guess < 1 or guess > 100:
        print("Your guess must be between 1 and 100.")
        continue
    guesses_taken = guesses_taken + 1
    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print("Correct! You guessed the number in", guesses_taken, "guesses.")
        break
else:
    # This 'else' belongs to the 'while', not to 'if'
    print("Sorry, you ran out of attempts. The number was", secret_number)

Key idea:

Adding Difficulty Levels

You can let the player choose how hard the game is by changing:

Example using three difficulty levels:

import random
print("Number Guessing Game")
print("Choose a difficulty level:")
print("1 - Easy   (1 to 10,   5 attempts)")
print("2 - Medium (1 to 100,  10 attempts)")
print("3 - Hard   (1 to 1000, 12 attempts)")
choice = input("Enter 1, 2, or 3: ")
if choice == "1":
    min_number = 1
    max_number = 10
    max_attempts = 5
elif choice == "2":
    min_number = 1
    max_number = 100
    max_attempts = 10
else:
    # Default to hard if anything else is entered
    min_number = 1
    max_number = 1000
    max_attempts = 12
secret_number = random.randint(min_number, max_number)
guesses_taken = 0
print(f"\nI'm thinking of a number between {min_number} and {max_number}.")
print(f"You have {max_attempts} attempts.")
while guesses_taken < max_attempts:
    guess_text = input("Your guess: ")
    try:
        guess = int(guess_text)
    except ValueError:
        print("Please enter a whole number.")
        continue
    if guess < min_number or guess > max_number:
        print(f"Stay within {min_number} and {max_number}.")
        continue
    guesses_taken += 1
    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print(f"Correct! You guessed the number in {guesses_taken} guesses.")
        break
if guesses_taken == max_attempts and guess != secret_number:
    print(f"You've used all attempts. The number was {secret_number}.")

This version introduces:

Adding a Play-Again Loop

You can wrap the whole game in another loop so that the player can choose to play again without restarting the program.

import random
def play_game():
    secret_number = random.randint(1, 100)
    max_attempts = 10
    guesses_taken = 0
    print("\nI'm thinking of a number between 1 and 100.")
    print("You have", max_attempts, "attempts.")
    while guesses_taken < max_attempts:
        guess_text = input("Your guess: ")
        try:
            guess = int(guess_text)
        except ValueError:
            print("Please enter a whole number.")
            continue
        if guess < 1 or guess > 100:
            print("Your guess must be between 1 and 100.")
            continue
        guesses_taken += 1
        if guess < secret_number:
            print("Too low!")
        elif guess > secret_number:
            print("Too high!")
        else:
            print("Correct! You guessed the number in", guesses_taken, "guesses.")
            return  # end the function when the player wins
    print("You ran out of attempts. The number was", secret_number)
print("Welcome to the Number Guessing Game!")
while True:
    play_game()
    again = input("\nDo you want to play again? (y/n): ").lower()
    if again != "y":
        print("Thanks for playing. Goodbye!")
        break

Here:

Extra Ideas to Improve Your Game

Once the basic game works, you can experiment with:

These additions use the same basic building blocks you’ve already used: input, conditions, loops, and simple math.


Practice Exercises

Try these small tasks to strengthen your understanding:

  1. Change the range and attempts
    • Make a version where the number is between 1 and 50 and the player only has 7 attempts.
  2. Guess counter feedback
    • After each guess, also print how many guesses have been used so far (for example: “This was guess 3 of 10”).
  3. Close-guess hint
    • If the player’s guess is within 5 of the secret number, print a message like “Very close!” in addition to “Too high” or “Too low”.
  4. Reverse roles (optional)
    • Make a different game where the computer tries to guess your number (you’ll need loops and conditions for this).

All of these variations build on the same basic number guessing game, and they are great practice to become more comfortable with Python.

Views: 16

Comments

Please login to add a comment.

Don't have an account? Register now!