Python by Projects

unit

Number Detective

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.

You will learn

  • 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 with str().
  • Let the computer pick a secret number with random.randint.
  • Compare values to get True or False, and choose with if, elif and else.
  • Repeat with a while loop until the guess is right.

Lesson 1: Numbers

A whole number such as 7, 0, or -12 is an integer — Python calls this the int type. No quotes are needed.

age = 11
print(age)

Output

11

Notice

11 is an integer — a whole number stored without quotes.

temperature = -4
score = 0
print(temperature)
print(score)

Output

-4
0

Notice

Integers include negatives and zero, not just counting numbers.

clue = 7
label = "7"
print(clue)
print(label)

Output

7
7

Notice

7 is 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)

Output

8

Notice

Python works out the math and prints the result.

print(10 - 4)

Output

6

Notice

- subtracts.

print(6 * 7)

Output

42

Notice

* multiplies.

marbles = 12
found = 5
print(marbles + found)

Output

17

Notice

Arithmetic works on saved numbers, not only typed-in ones.

print(17 // 5)

Output

3

Notice

// gives how many whole groups fit — 17 // 5 is 3.

print(17 % 5)

Output

2

Notice

% gives what is left over after those groups — 17 % 5 is 2.

One catch: input() always gives text, even when someone types digits. Use int() to turn digit-text into an integer and str() to turn an integer back into text. This is type conversion.

typed = "27"
number = int(typed)
print(number)

Output

27

Notice

int("27") becomes the number 27, ready for arithmetic.

count = 5
count_text = str(count)
print(f"As text, the count is {count_text}.")

Output

As text, the count is 5.

Notice

str() turns a number into text — the reverse of int().

Try it yourself

guess = int(input("Enter an integer: "))
print(f"You entered {guess}.")

Notice

Wrap input() in int() whenever you need a number from the keyboard.

Lesson 2: The Computer Picks and Judges

import random brings in Python's random-number tools. random.randint(1, 100) then picks an integer from 1 through 100 — both ends can be picked.

import random

Notice

import random loads 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)
import random
print(random.randint(1, 6))

Output

2

Notice

Now random.randint(1, 6) rolls a number 1 through 6 (both ends can be picked).

import random
print(random.randint(1, 100))

Output

73

Notice

Change the two numbers to change the range.

import random
secret = random.randint(1, 10)
print(f"(sneak peek) the secret is {secret}")

Output

(sneak peek) the secret is 2

Notice

Save 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, True or False. Use == equal, != not equal, < less than, > greater than.

print(7 == 7)

Output

True

Notice

A comparison reports True or False — a boolean.

print(3 < 10)
print(10 < 3)

Output

True
False

Notice

< is True only when the left side is smaller.

print(5 != 4)
print(5 != 5)

Output

True
False

Notice

!= is "not equal" — True when the two values differ.

print(5 > 2)
print(2 > 5)

Output

True
False

Notice

> is "greater than" — the mirror of <. Now you have all four: ==, !=, <, >.

secret = 42
guess = 30
print(guess == secret)
print(guess < secret)

Output

False
True

Notice

You 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)

Output

True

Notice

The True/False answer can be saved in a variable and reused later.

Lesson 3: Make a Choice

An if statement runs its indented lines only when a comparison is True.

guess = 30
secret = 42
if guess < secret:
    print("Too low!")

Output

Too low!

Notice

The indented print runs only because 30 < 42 is True.

guess = 50
secret = 42
if guess < secret:
    print("Too low!")
print("(done checking)")

Output

(done checking)

Notice

When the if is False, Python skips the indented line and carries on.

guess = 30
secret = 42
if guess == secret:
    print("Found it!")
else:
    print("Keep trying.")

Output

Keep trying.

Notice

else runs when the if is False — exactly one of the two always runs.

elif adds more choices between if and else. Python checks them top to bottom and takes the first comparison that is True.

guess = 30
secret = 42
if guess > secret:
    print("Too high!")
elif guess < secret:
    print("Too low!")
else:
    print("Just right!")

Output

Too low!

Notice

elif is checked only when the tests above it were False.

temperature = 15
if temperature > 25:
    print("Hot")
elif temperature > 10:
    print("Warm")
else:
    print("Cold")

Output

Warm

Notice

Python 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!")

Output

Too high!

Notice

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 yourself

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!")

Notice

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 while loop repeats its indented lines while a comparison stays True. Tally guesses on paper — do not add a guess-counting variable (the computer learns that trick in a later unit).

Try it yourself

answer = input("Type the word stop to finish: ")
while answer != "stop":
    print("Not yet...")
    answer = input("Type the word stop to finish: ")
print("Stopped!")

Notice

The loop repeats while the test is True; typing stop makes it False and the loop ends.

Try it yourself

secret = 7
guess = int(input("Guess the number: "))
while guess != secret:
    print("Nope, guess again.")
    guess = int(input("Guess again: "))
print("Correct!")

Notice

Each trip asks again; when the guess matches the secret, the loop stops.

Try it yourself

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!")

Notice

Put an if inside 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.")

Output

Too high!
Too low!
Too high!
Correct! Case closed.

Notice

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 one input() line.

Try it yourself

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.")

Notice

The full detective game — random picks, while repeats, if/else hints.

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 yourself

# 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!")

The traceback points to the comparison: input() made text, but secret is an integer. Convert the typed guess before comparing it.

Try it yourself

# 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!")

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)

Output

True

Notice

While the guess does NOT equal the secret, guess != secret is True — the loop keeps going.

guess = 7
secret = 7
print(guess != secret)

Output

False

Notice

The moment the guess matches, guess != secret is False and 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!")

Output

5
2
8
8
8
7
Got it!

Notice

The computer keeps guessing until a guess equals the secret. guess starts at 0, 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 a while loop 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!")

Output

3
9
7
Got it!

Notice

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. The print(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 one input() line and ends on the same Got it!.

Try it yourself

import random
secret = random.randint(1, 10)
guess = 0
while guess != secret:
    guess = int(input("Guess a number 1-10: "))
print("Got it!")

Notice

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).

Recap

  • Integers need no quotes; 17 // 5 is 3 and 17 % 5 is 2.
  • input() always gives text, so wrap it in int() before doing math or comparing.
  • random.randint(1, 100) picks from 1 through 100; random.seed makes the picks repeat.
  • ==, !=, < and > give a boolean, and if/elif/else runs the first branch whose test is True.
  • A while loop repeats while its test stays True, so the correct guess ends the game.

You can now build the whole Number Detective guessing game.

Go to the exercises (10)

For parents and teachers: report a problem