Home · Academy · Robotics & Coding · Python Fundamentals · Project: Number Guessing Game

Project: Number Guessing Game

Combine random, while, if and input to build a working number guessing game.

PROJECT COMPASS

What will you use this page for?

Core idea

We build a small, fully working game where the computer holds a secret number and the player tries to guess it, using random , while , if and input .

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Forgetting to convert to int If you write guess = input(...) , then guess is text. The comparison "50" < secret_number raises an error. Fix: int(input(...)) . Forgetting the break Without break on a correct guess, the loop never ends; the program keeps asking even after finding the right answer. Two separate ifs…

Next connection

Project: Timetable Checker: Using a list and a loop, a program that checks which books should be in your bag based on the day's lessons.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration45–75 min
PrerequisiteModules and Libraries
ContentProject guide · 1,864 words
Last updated

One-sentence summary

We build a small, fully working game where the computer holds a secret number and the player tries to guess it, using random, while, if and input.

Why does it matter?

So far we have learned loops, conditions and libraries one at a time. A real program brings these pieces together. A number guessing game is a great first project for this: it is short, but it contains the whole skeleton of a program.

In this project we will combine:

In short, this lesson is the bridge between "I know the commands" and "I wrote a program."

The plan for the game

Before writing code, let's think through the game step by step in plain language. In earlier modules we called this pseudocode.

Start
Computer picks a secret number between 1 and 100
Set the guess count to 0
Repeat:
  Get a guess from the user
  Increase the guess count by 1
  If the guess is smaller than the secret number
    print "Try a bigger number"
  If the guess is bigger than the secret number
    print "Try a smaller number"
  Otherwise (the guess is correct)
    print "Congratulations" and stop the loop
End

This plan builds the whole game on three ideas: a secret number, a repetition (loop) and a decision made on every turn. Now let's translate the pieces into Python one by one.

Getting to know the building blocks

A secret number with random

random is a standard library that comes with Python; it is used to create random numbers. Before using it, we bring it into the program with import.

import random

secret_number = random.randint(1, 100)
print(secret_number)  # for testing only; we won't show it in the game

random.randint(1, 100) gives a random whole number between 1 and 100, including both ends. Every time you run it, you see a different number.

Getting a guess with input

input always returns text (a string). To compare numbers, we convert the value to a whole number with int.

guess = int(input("Guess a number between 1 and 100: "))
print(guess + 1)  # now we can treat it as a number

If we forget the int(...), we try to compare the text "50" with a number and get an error.

Repeating with while

A while loop repeats the lines inside it as long as its condition is true. Because we want it to keep asking until the guess is correct, we use while True and leave with break on a correct answer. break is the command that ends a loop immediately.

The indentation here (4 spaces) matters a lot: Python uses indentation to decide whether a line is inside or outside a while or if block.

counter = 0
while counter < 3:
    counter = counter + 1
    print("Turn", counter)

This small example prints three times and stops. In the game, we will set the condition as "until the correct answer arrives."

The full game code

Now we combine all the pieces. The code below runs from start to finish:

import random

secret_number = random.randint(1, 100)
guesses = 0

while True:
    guess = int(input("Guess a number between 1 and 100: "))
    guesses = guesses + 1

    if guess < secret_number:
        print("Try a bigger number.")
    elif guess > secret_number:
        print("Try a smaller number.")
    else:
        print(f"Well done! You found it in {guesses} guesses.")
        break

The logic matches the plan exactly. if means too small, elif means too big, and else means the guess is correct, so break ends the game. The f"..." is an f-string: it places the value inside the curly braces {guesses} into the text.

Test scenarios

Writing a program is not enough; we should try it with different inputs. Suppose the secret number is 42:

Test scenarios table
GuessWhat appearsNext step
50Try a smaller number.Go down to 1–49
25Try a bigger number.Go up to 26–49
42Well done! You found it in 3 guesses.Game ends

If you split the range in half every turn (this is called binary search), you can find any number from 1 to 100 in at most 7 guesses. Play your own game a few times and test this.

A bug and its fix

The first time I wrote it, I tried a version with two separate if statements instead of one chain:

if guess < secret_number:
    print("Try a bigger number.")
if guess > secret_number:      # this should have been elif
    print("Try a smaller number.")
else:
    print("Well done!")

The problem was this: the else attached to the second if only covered the "not bigger" case. When the guess was smaller than the secret number, it printed both "Try a bigger number" and, by mistake, "Well done!"

The fix was to change the second if into elif. That joined the three cases into a single decision chain: smaller, bigger, or correct. In a program, wiring the "otherwise" path correctly is just as important as writing the condition.

Mini practice

Add your own improvements on top of the working game. A few ideas, from easy to harder:

  1. Limit the guesses: Use while guesses < 7 instead of while True; if the tries run out, print the secret number.
  2. Change the range: Make it harder with random.randint(1, 500).
  3. "You're very close" hint: If the difference between the guess and the secret number is smaller than 5, print an extra message.
  4. Play again: When the game ends, ask "Do you want to play again?" and wrap it in an outer loop.

A starting point for the limited-guess version:

while guesses < 7:
    guess = int(input("Your guess: "))
    guesses = guesses + 1
    # add hints here
    if guess == secret_number:
        print("You won!")
        break

Project strengthening plan

A working demonstration is not enough for Project: Number Guessing Game. A strong project also makes its aim, user, limits, test conditions and failed attempts visible. Use the context of a command-line tool that checks a daily timetable to produce a short working Python 3 program, sample inputs and expected outputs. Although the lesson aims to “Combine random, while, if and input to build a working number guessing game”, do not present an unmeasured result as a confirmed success.

1. Project summary and scope

Write three sentences: What problem are you solving, who is affected by it, and what will the first version deliberately not do? Stating what is outside the scope does not weaken a project; it makes the project finishable. Describe the connection between The plan for the game and A secret number with random as the main assumption, then name the test that can confirm or reject it.

2. Acceptance criteria

Do not leave an acceptance criterion for “Project: Number Guessing Game” as a vague statement such as “it works”. Choose an observable measure such as time, distance, correct trials, screen width or user steps. When direct measurement is difficult, record whether the same behaviour appears in three consecutive trials.

3. Test matrix

3. Test matrix table
TestConditionExpectedActual resultNext decision
NormalStandard input and complete setupThe core task is completedFill in during the testKeep it or make a small improvement
BoundaryLowest or highest accepted valueThe system remains stableFill in during the testReview the threshold or rule
ErrorMissing, wrong or unexpected inputA safe and clear responseFill in during the testAdd error handling
RepeatAt least three trials under the same conditionSimilar resultsFill in during the testInvestigate the source of inconsistency

4. Version log

For every version of “Project: Number Guessing Game”, record the date, the one main decision changed, the reason and the test result. A first version that fails is evidence about which assumption involving The plan for the game or A secret number with random should be reconsidered. Remove personal information and private background details from images.

5. Presentation and self-review

Prepare a two-minute explanation of “Project: Number Guessing Game”: the problem, the solution approach, the most important result for a command-line tool that checks a daily timetable, and the next step. Instead of saying the project is complete, state which part has been verified and which part still needs development.

Common mistakes

Forgetting to convert to int

If you write guess = input(...), then guess is text. The comparison "50" < secret_number raises an error. Fix: int(input(...)).

Forgetting the break

Without break on a correct guess, the loop never ends; the program keeps asking even after finding the right answer.

Two separate ifs instead of elif

As we saw above, independent if statements can produce unexpected results. For mutually exclusive cases, use an if / elif / else chain.

Breaking the indentation

Lines inside while and if blocks must be indented 4 spaces. Inconsistent indentation makes Python raise an IndentationError.

Safety note

This lesson is entirely about running your own code on your own computer. Before running unfamiliar code you find online, ask an adult, and never ask for or store personal details such as names, addresses or phone numbers in your games.

Lesson summary

Review questions

  1. What are the smallest and largest numbers random.randint(1, 100) can produce?
  2. Why do we convert the value from input with int?
  3. Which command ends the while True loop in the game?
  4. Why is elif more correct than a second if for the second condition?
  5. How would you write the loop condition to limit the game to 7 guesses?

Answers

  1. The smallest is 1 and the largest is 100; both ends are included.
  2. input returns text; without int, a number comparison raises an error.
  3. When the guess is correct, the break in the else block ends the loop.
  4. elif is checked only if the previous condition is false, so smaller, bigger and correct form one decision chain. Two separate if statements can cause wrong matches.
  5. Write it as while guesses < 7: and print the secret number when the tries run out.

Source and verification note

For “Project: Number Guessing Game”, verification focuses on whether the relationship between The plan for the game and A secret number with random remains consistent across examples. Code examples follow Python 3 syntax. Small differences may appear between environments, so examples should first be tested in a safe online editor or a local development setup.

Next lesson

Project: Timetable Checker: Using a list and a loop, a program that checks which books should be in your bag based on the day's lessons.

Start QuizBack to Python Fundamentals
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.