The computer picks a secret number. Can you find it in only a few guesses? By the end of this unit you will build the whole guessing game yourself.
Each new idea comes as a short ladder: the simplest version, then one small twist, then a real use. The Notice line after each rung points at the single new thing.
-
Do arithmetic with integers, including
//for whole groups and%for the remainder. -
Turn typed text into a number with
int(), and a number into text withstr(). -
Let the computer pick a secret number with
random.randint. -
Compare values to get
TrueorFalse, and choose withif,elifandelse. -
Repeat with a
whileloop until the guess is right.
-
Lesson 1: Numbers
A whole number such as
7,0, or-12is an integer — Python calls this theinttype. No quotes are needed.age = 11 print(age)Scroll the code for more ↓
Output
1111is an integer — a whole number stored without quotes.temperature = -4 score = 0 print(temperature) print(score)Scroll the code for more ↓
Output
-4 0Integers include negatives and zero, not just counting numbers.
clue = 7 label = "7" print(clue) print(label)Scroll the code for more ↓
Output
7 77is an integer;"7"is text that only looks like one — Python treats them differently (you will see how in a moment).Integers can do arithmetic: add
+, subtract-, multiply*.//tells how many whole groups fit, and%tells what is left over.print(5 + 3)Scroll the code for more ↓
Output
8Python works out the math and prints the result.
print(10 - 4)Scroll the code for more ↓
Output
6-subtracts.print(6 * 7)Scroll the code for more ↓
Output
42*multiplies.marbles = 12 found = 5 print(marbles + found)Scroll the code for more ↓
Output
17Arithmetic works on saved numbers, not only typed-in ones.
print(17 // 5)Scroll the code for more ↓
Output
3//gives how many whole groups fit —17 // 5is3.print(17 % 5)Scroll the code for more ↓
Output
2%gives what is left over after those groups —17 % 5is2.One catch:
input()always gives text, even when someone types digits. Useint()to turn digit-text into an integer andstr()to turn an integer back into text. This is type conversion.typed = "27" number = int(typed) print(number)Scroll the code for more ↓
Output
27int("27")becomes the number27, ready for arithmetic.count = 5 count_text = str(count) print(f"As text, the count is {count_text}.")Scroll the code for more ↓
Output
As text, the count is 5.str()turns a number into text — the reverse ofint().Try it guess = int(input("Enter an integer: ")) print(f"You entered {guess}.")Scroll the code for more ↓
Wrap
input()inint()whenever you need a number from the keyboard.Lesson 2: The Computer Picks and Judges
import randombrings in Python's random-number tools.random.randint(1, 100)then picks an integer from 1 through 100 — both ends can be picked.import randomScroll the code for more ↓
import randomloads Python's random toolbox — it prints nothing by itself, but the tools are now ready to use.A seed fixes the starting point of the random-number recipe. With the same seed, the "random" numbers come out the same on every run, so your printed results match the ones shown here. Change the seed, or leave this cell out, to get different numbers.
random.seed(1)Scroll the code for more ↓
import random print(random.randint(1, 6))Scroll the code for more ↓
Output
2Now
random.randint(1, 6)rolls a number 1 through 6 (both ends can be picked).import random print(random.randint(1, 100))Scroll the code for more ↓
Output
73Change the two numbers to change the range.
import random secret = random.randint(1, 10) print(f"(sneak peek) the secret is {secret}")Scroll the code for more ↓
Output
(sneak peek) the secret is 2Save the pick in a variable to use later — this is how the game hides its secret.
Now the computer must judge a guess. A comparison asks a yes-or-no question; its answer is a boolean,
TrueorFalse. Use==equal,!=not equal,<less than,>greater than.print(7 == 7)Scroll the code for more ↓
Output
TrueA comparison reports
TrueorFalse— a boolean.print(3 < 10) print(10 < 3)Scroll the code for more ↓
Output
True False<is True only when the left side is smaller.print(5 != 4) print(5 != 5)Scroll the code for more ↓
Output
True False!=is "not equal" — True when the two values differ.print(5 > 2) print(2 > 5)Scroll the code for more ↓
Output
True False>is "greater than" — the mirror of<. Now you have all four:==,!=,<,>.secret = 42 guess = 30 print(guess == secret) print(guess < secret)Scroll the code for more ↓
Output
False TrueYou can compare saved numbers — exactly what the game needs to judge a guess.
secret = 42 guess = 30 is_too_low = guess < secret print(is_too_low)Scroll the code for more ↓
Output
TrueThe
True/Falseanswer can be saved in a variable and reused later.Lesson 3: Make a Choice
An
ifstatement runs its indented lines only when a comparison isTrue.guess = 30 secret = 42 if guess < secret: print("Too low!")Scroll the code for more ↓
Output
Too low!The indented
printruns only because30 < 42is True.guess = 50 secret = 42 if guess < secret: print("Too low!") print("(done checking)")Scroll the code for more ↓
Output
(done checking)When the
ifis False, Python skips the indented line and carries on.guess = 30 secret = 42 if guess == secret: print("Found it!") else: print("Keep trying.")Scroll the code for more ↓
Output
Keep trying.elseruns when theifis False — exactly one of the two always runs.elifadds more choices betweenifandelse. Python checks them top to bottom and takes the first comparison that isTrue.guess = 30 secret = 42 if guess > secret: print("Too high!") elif guess < secret: print("Too low!") else: print("Just right!")Scroll the code for more ↓
Output
Too low!elifis checked only when the tests above it were False.temperature = 15 if temperature > 25: print("Hot") elif temperature > 10: print("Warm") else: print("Cold")Scroll the code for more ↓
Output
WarmPython takes the FIRST branch whose test is True, then stops checking the rest.
secret = 37 guess = 52 if guess > secret: print("Too high!") elif guess < secret: print("Too low!") else: print("You found it!")Scroll the code for more ↓
Output
Too high!With a fixed secret and guess, the one-guess game runs here and gives the same kind of verdict as the real version below.
Try it import random secret = random.randint(1, 100) guess = int(input("Your one guess: ")) if guess > secret: print("Too high!") elif guess < secret: print("Too low!") else: print("You found it!")Scroll the code for more ↓
Put it together and the detective gives a verdict for one real guess.
Lesson 4: The Full Game
One guess is not much of a game. A
whileloop repeats its indented lines while a comparison staysTrue. Tally guesses on paper — do not add a guess-counting variable (the computer learns that trick in a later unit).Try it answer = input("Type the word stop to finish: ") while answer != "stop": print("Not yet...") answer = input("Type the word stop to finish: ") print("Stopped!")Scroll the code for more ↓
The loop repeats while the test is True; typing
stopmakes it False and the loop ends.Try it secret = 7 guess = int(input("Guess the number: ")) while guess != secret: print("Nope, guess again.") guess = int(input("Guess again: ")) print("Correct!")Scroll the code for more ↓
Each trip asks again; when the guess matches the secret, the loop stops.
Try it secret = 7 guess = int(input("Guess the number: ")) while guess != secret: if guess > secret: print("Too high!") else: print("Too low!") guess = int(input("Guess again: ")) print("Got it!")Scroll the code for more ↓
Put an
ifinside the loop to give a smarter hint on every guess.secret = 37 guess = 50 while guess != secret: if guess > secret: print("Too high!") else: print("Too low!") # scripted player: the next guess (stands in for typing) if guess == 50: guess = 25 elif guess == 25: guess = 40 else: guess = secret print("Correct! Case closed.")Scroll the code for more ↓
Output
Too high! Too low! Too high! Correct! Case closed.A notebook that runs by itself cannot wait for typing, so a scripted player makes the guesses 50, 25, 40, then 37. The last scripted line,
guess = secret, is the player finally getting it right. The loop body runs once for every wrong guess — three trips here — and the hint changes each trip. The real version below swaps the scripted lines inside the loop for oneinput()line.Try it import random secret = random.randint(1, 100) guess = int(input("Guess the secret number: ")) while guess != secret: if guess > secret: print("Too high!") else: print("Too low!") guess = int(input("Guess again: ")) print("Correct! Case closed.")Scroll the code for more ↓
The full detective game —
randompicks,whilerepeats,if/elsehints.Detectives inspect clues; programmers inspect error messages. The next snippet is intentionally broken. Run it, type
20, and read the traceback from the bottom: what two types was it asked to compare?Try it # Intentionally broken: read the traceback to find the clue. secret = 50 guess = input("Guess a number: ") if guess < secret: print("Too low!") else: print("Too high or correct!")Scroll the code for more ↓
The traceback points to the comparison:
input()made text, butsecretis an integer. Convert the typed guess before comparing it.Try it # Fixed: both compared values are integers. secret = 50 guess = int(input("Guess a number: ")) if guess < secret: print("Too low!") else: print("Too high or correct!")Scroll the code for more ↓
Play your full game with a partner. Mark one line on paper for every guess, then swap seats and play again.
Algorithm Extension
The sentinel-loop pattern Spotlight (repeat until a stop signal), gathered here for reference — read in class; its exercise is the last one in the exercises notebook.
Pattern Spotlight: Repeat until done (sentinel loop)
You know when you're done; the program must ask "done yet?" every pass.
Computational-thinking contrast: Unlike a loop that runs a fixed number of times, a sentinel loop repeats until its condition says the job is done.
guess = 3 secret = 7 print(guess != secret)Scroll the code for more ↓
Output
TrueWhile the guess does NOT equal the secret,
guess != secretisTrue— the loop keeps going.guess = 7 secret = 7 print(guess != secret)Scroll the code for more ↓
Output
FalseThe moment the guess matches,
guess != secretisFalseand the loop STOPS — that match is the sentinel.import random secret = 7 guess = 0 while guess != secret: guess = random.randint(1, 10) print(guess) print("Got it!")Scroll the code for more ↓
Output
5 2 8 8 8 7 Got it!The computer keeps guessing until a guess equals the secret.
guessstarts at0, a number that can never be the secret, so the loop always runs at least once. Nobody — not even the programmer — knows ahead of time how many trips it will take: run the cell again and count. That is why this is awhileloop and not the same lines copied a fixed number of times. The matching guess is the sentinel that stops it.secret = 7 guess = 0 while guess != secret: # scripted player: the next guess (stands in for typing) if guess == 0: guess = 3 elif guess == 3: guess = 9 else: guess = secret print(guess) print("Got it!")Scroll the code for more ↓
Output
3 9 7 Got it!A scripted player guesses 3, 9, then 7 (the last scripted line,
guess = secret, is the player finally getting it right), so the loop body runs three times — once per guess. Theprint(guess)line is there so you can watch the guesses; the real game below has no such line because you see what you type. It replaces the scripted lines with oneinput()line and ends on the sameGot it!.Try it import random secret = random.randint(1, 10) guess = 0 while guess != secret: guess = int(input("Guess a number 1-10: ")) print("Got it!")Scroll the code for more ↓
The real game — the loop repeats, reading a NEW guess each time, until the guess equals the secret (the sentinel that ends it). It uses
input(), so this cell is display-only (not run here).-
Integers need no quotes;
17 // 5is3and17 % 5is2. -
input()always gives text, so wrap it inint()before doing math or comparing. -
random.randint(1, 100)picks from 1 through 100;random.seedmakes the picks repeat. -
==,!=,<and>give a boolean, andif/elif/elseruns the first branch whose test isTrue. -
A
whileloop repeats while its test staysTrue, so the correct guess ends the game.
You can now build the whole Number Detective guessing game.
-