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.
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:
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.
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("Too low. Try a bigger number.")
elif guess > secret_number:
print("Too high. Try a smaller number.")
else:
print(f"Correct! You got it in {guesses_taken} guesses.")
break # stop the loop — the game is over.
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.
int() around input — comparing text to a number always fails.int(input(...)). Typed input is text until you convert it.secret_number = random.randint(...) inside the loop — it picks a new secret every guess, so you can never win.break — the loop never stops, even after a correct guess.break in the else so the game ends when the guess is right.= instead of == when comparing — one assigns, two compares.== 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.
import random
from unittest.mock import patch
import builtins
def play_game(secret, guesses):
"""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."""
taken = 0
for guess in guesses:
taken += 1
if guess == secret:
return taken
return None # never guessed it
def test_correct_first_try():
"""If the player guesses the secret immediately, it takes 1 try."""
assert play_game(42, [42]) == 1
def test_takes_three_tries():
"""If the right answer is the third guess, it returns 3."""
assert play_game(50, [10, 90, 50]) == 3
def test_never_guesses():
"""If the player never guesses it, the result is None (not a crash)."""
assert play_game(7, [1, 2, 3]) is None
def test_secret_is_in_range():
"""The secret number must always be between 1 and 100."""
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.
What it expects
A number like 42, typed and then Enter pressed.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.
python3 guessing_game.pyThen 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.
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.ValueError: invalid literal for int()42.break is missing or in the wrong place. It must run when the guess equals the secret.int(...).// Jenkinsfile — runs the tests automatically every time the code changes.
pipeline {
agent any // run on any available machine
stages {
stage('Get the code') {
steps { checkout scm } // download the latest code
}
stage('Install Python tools') {
steps {
sh 'python3 -m venv venv' // make a clean workspace
sh '. venv/bin/activate && pip install pytest' // install the test tool
}
}
stage('Run the tests') {
steps {
sh '. venv/bin/activate && pytest -v' // run every test, show each result
}
}
}
post {
success { echo 'All tests passed — the game works.' } // good news
failure { echo 'A test failed — something broke. Look above.' } // alert: fix it
}
}
You have the working game. Now make it yours — each of these adds one new idea:
- Limit the guesses. Give the player only 7 tries, then reveal the answer. (Teaches: counting toward a limit.)
- Let them play again. After winning, ask “Play again? (y/n)” and restart if yes. (Teaches: an outer loop.)
- Handle bad input gracefully. If they type “abc”, say “please type a number” instead of crashing. (Teaches: try/except.)
- Make the computer guess your number. Flip the roles — the computer guesses and you say higher/lower. (Teaches: binary search thinking.)