thecodex.expert · The Codex Family of Knowledge
Tier 0 · Absolute Beginner · Python Project

Number Guessing Game

Your very first program with a memory and a decision: the computer picks a secret number, and you guess until you get it. You will learn how a program asks a question, checks an answer, and repeats.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want a tiny game: the computer thinks of a number between 1 and 100, and the player keeps guessing. After each guess the computer says “too high” or “too low” until the player gets it right. Simple — but it teaches the three things every program does: ask, decide, and repeat.

Where this shows up in real life: every time an app checks your password, validates a form, or keeps asking until you give a valid answer, it is doing exactly this — take input, compare it to something, and loop until the condition is met. Learn it here in 15 lines, and you have learned the heartbeat of almost every program.

2 How to Think About It

Before writing any code, picture the game as a loop with a decision inside it. You do not need to know Python yet — you just need to know the shape of what happens:

The shape of the game — in plain English
1. Pick a secret number once, at the start. → 2. Ask the player to guess. → 3. Compare the guess to the secret: lower, higher, or equal? → 4. If not equal, go back to step 2. If equal, celebrate and stop. That is the whole program. Everything below is just saying this in Python.

Too low

Too high

Correct!

Computer picks a secret number 1-100

Ask the player to guess

Is the guess right?

Say 'too low'

Say 'too high'

Show how many guesses it took

Game over

3 The Build — explained part by part

Here is the complete game. Read each line’s plain-English note below it — you should be able to understand the whole program from the notes alone, without knowing any Python in advance.

Pythonguessing_game.py
import random

# The computer secretly picks a whole number from 1 to 100.
secret_number = random.randint(1, 100)

# We count how many guesses the player takes.
guesses_taken = 0

print("I am thinking of a number between 1 and 100.")

# Keep asking until the player guesses right.
while True:
    # Ask the player for a guess and turn their text into a number.
    guess = int(input("Your guess: "))
    guesses_taken = guesses_taken + 1

    if guess < secret_number:
        print(&quot;Too low. Try a bigger number.&quot;)
    elif guess > secret_number:
        print(&quot;Too high. Try a smaller number.&quot;)
    else:
        print(f&quot;Correct! You got it in {guesses_taken} guesses.&quot;)
        break   # stop the loop — the game is over.
What each part does — in plain words
import random — we borrow Python’s built-in “dice roller.” It can pick random numbers for us.

secret_number = random.randint(1, 100) — pick one random whole number from 1 to 100 and remember it. This is the number the player must find.

guesses_taken = 0 — start a counter at zero so we can tell the player how many tries they used.

while True: — “keep doing the following over and over.” This is the repeat part. It only stops when we tell it to.

guess = int(input("Your guess: ")) — show the player a prompt, read what they type, and turn that text into a number (input always gives text; int turns “42” into the number 42).

if / elif / else — the decision. Compare the guess to the secret: if it is smaller say “too low,” if bigger say “too high,” otherwise it must be correct.

break — the off-switch for the loop. The moment the guess is right, we stop repeating and the game ends.
Common mistakes — and how to avoid them
✗ Forgetting int() around input — comparing text to a number always fails.
✓ Always convert: int(input(...)). Typed input is text until you convert it.
✗ Putting secret_number = random.randint(...) inside the loop — it picks a new secret every guess, so you can never win.
✓ Pick the secret once, before the loop starts.
✗ Forgetting break — the loop never stops, even after a correct guess.
✓ Add break in the else so the game ends when the guess is right.
✗ Using = instead of == when comparing — one assigns, two compares.
✓ Use == to ask “are these equal?” Python will error on = here, which is a helpful hint.

4 Test & Prove Each Part

How do we know the game works without playing it a hundred times by hand? We write small tests — each one checks one rule and proves it. Read each test’s one-line description; together they prove the whole game behaves.

Guessing the secret on the first try counts as 1 try
When the answer is the third guess, it correctly returns 3
If the player never guesses it, we get a clean result — not a crash
The secret number is always between 1 and 100, every single time
Pythontest_guessing_game.py
import random
from unittest.mock import patch
import builtins


def play_game(secret, guesses):
    &quot;&quot;&quot;A testable version of the game: we hand it the secret number and a
    list of guesses, and it returns how many tries it took.&quot;&quot;&quot;
    taken = 0
    for guess in guesses:
        taken += 1
        if guess == secret:
            return taken
    return None   # never guessed it


def test_correct_first_try():
    &quot;&quot;&quot;If the player guesses the secret immediately, it takes 1 try.&quot;&quot;&quot;
    assert play_game(42, [42]) == 1


def test_takes_three_tries():
    &quot;&quot;&quot;If the right answer is the third guess, it returns 3.&quot;&quot;&quot;
    assert play_game(50, [10, 90, 50]) == 3


def test_never_guesses():
    &quot;&quot;&quot;If the player never guesses it, the result is None (not a crash).&quot;&quot;&quot;
    assert play_game(7, [1, 2, 3]) is None


def test_secret_is_in_range():
    &quot;&quot;&quot;The secret number must always be between 1 and 100.&quot;&quot;&quot;
    for _ in range(1000):
        n = random.randint(1, 100)
        assert 1 <= n <= 100

Run them with pytest -v. Each test sets up a tiny situation and checks the result. Green means the rule holds; red means we broke something and need to look. This is how real programmers stay confident their code still works after every change.

5 The Interface

Even a tiny program has an interface — the way a person interacts with it. Here is its contract, documented plainly, the same way a professional would describe any tool.

INPUTYour guessa whole number 1–100, typed by the player
What it expects
A number like 42, typed and then Enter pressed.
OUTPUTFeedbackone of three replies
What it returns
"Too low. Try a bigger number."
"Too high. Try a smaller number."
"Correct! You got it in N guesses."

6 Run It & Automate It

Save the code as guessing_game.py and run it. Then play — it is genuinely fun.

Run it locally
python3 guessing_game.py
Then type a number, press Enter, and follow the “too high / too low” hints until you win.

In a real project you would not run the tests by hand every time — a tool (here, Jenkins) runs them automatically whenever the code changes, and tells you immediately if something broke. Every line below has a plain explanation.

What you should see when it works
Terminala real run
I am thinking of a number between 1 and 100.
Your guess: 50
Too high. Try a smaller number.
Your guess: 25
Too low. Try a bigger number.
Your guess: 37
Too high. Try a smaller number.
Your guess: 31
Correct! You got it in 4 guesses.
If it breaks — how to fix it
🚨 ValueError: invalid literal for int()
You typed something that is not a whole number (like “ten” or a blank). Type digits only, e.g. 42.
🚨 The game never ends, even when I guess right.
Your break is missing or in the wrong place. It must run when the guess equals the secret.
🚨 It says “too high” even for small numbers.
You likely compared text to a number. Make sure the guess goes through int(...).
GroovyJenkinsfile
// Jenkinsfile — runs the tests automatically every time the code changes.
pipeline {
    agent any                                  // run on any available machine

    stages {
        stage(&#x27;Get the code&#x27;) {
            steps { checkout scm }             // download the latest code
        }
        stage(&#x27;Install Python tools&#x27;) {
            steps {
                sh &#x27;python3 -m venv venv&#x27;                       // make a clean workspace
                sh &#x27;. venv/bin/activate && pip install pytest&#x27;  // install the test tool
            }
        }
        stage(&#x27;Run the tests&#x27;) {
            steps {
                sh &#x27;. venv/bin/activate && pytest -v&#x27;           // run every test, show each result
            }
        }
    }

    post {
        success { echo &#x27;All tests passed — the game works.&#x27; }   // good news
        failure { echo &#x27;A test failed — something broke. Look above.&#x27; }  // alert: fix it
    }
}
🎯 Try this next — make it yours

You have the working game. Now make it yours — each of these adds one new idea:

  1. Limit the guesses. Give the player only 7 tries, then reveal the answer. (Teaches: counting toward a limit.)
  2. Let them play again. After winning, ask “Play again? (y/n)” and restart if yes. (Teaches: an outer loop.)
  3. Handle bad input gracefully. If they type “abc”, say “please type a number” instead of crashing. (Teaches: try/except.)
  4. Make the computer guess your number. Flip the roles — the computer guesses and you say higher/lower. (Teaches: binary search thinking.)
What you learned
You just learned the three pillars every program is built on: input (asking the player), decisions (if / elif / else), and loops (while + break). You also met random numbers, a counter, and — importantly — how to prove your code works with tests and how a CI tool watches for breakage. Next, try a project that combines these with lists and functions. Related reference: Control Flow & Loops, random.