On this page

Guided Exercise: Build a Number‑Guessing Game

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Objective​

This challenge requires you to combine the core ideas from Module 2: Boolean logic, conditional statements, for/while loops, and basic error handling. You will build an interactive game where the computer selects a secret number and the user attempts to guess it.

The goal is to design a program that responds intelligently to user input, provides feedback, and continues looping until the correct answer is found.

Requirements​

Your program must:

These requirements ensure that you apply every major concept from this module.

Step‑by‑Step Guidance​

1. Generate the Secret Number​

Use Python’s random module to generate a number.


import random



secret = random.randint(1, 100)

This selects a number between 1 and 100, inclusive.

2. Create a Loop for Repeated Guesses​

A while loop allows the game to continue until the user succeeds.


guess = None



while guess != secret:

    # ask for input inside the loop

The loop condition ensures repetition until the correct guess is entered.

3. Read and Validate User Input​

Use try and except to prevent the program from crashing when the user enters invalid data.


try:

    guess = int(input("Enter your guess (1–100): "))

except ValueError:

    print("Please enter a valid number.")

    continue

If conversion fails, the loop continues without further processing.

4. Compare the Guess to the Secret Number​

Use conditional statements to provide feedback.


if guess < secret:

    print("Too low.")

elif guess > secret:

    print("Too high.")

else:

    print("Correct!")

Only one branch runs per iteration.

5. End the Game When the Guess Is Correct​

When the user guesses correctly, the loop condition becomes False and the program ends naturally.

Full Example Solution​

This implementation satisfies all requirements and demonstrates clean, readable control flow.


import random



secret = random.randint(1, 100)

guess = None



while guess != secret:

    try:

        guess = int(input("Enter your guess (1–100): "))

    except ValueError:

        print("Please enter a valid number.")

        continue



    if guess < secret:

        print("Too low.")

    elif guess > secret:

        print("Too high.")

    else:

        print("Correct! You guessed the number.")

What You Should Learn from This Challenge​

By completing this exercise, you demonstrate that you can:

This challenge marks the transition from basic syntax to real program design, preparing you for more advanced logic and larger projects in the next modules.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Error Handling

Next

Core Data Structures