Exit slides Esc

Number Detective

Slide 1 of 62

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

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

  3. age = 11
    print(age)

    Output

    11
    

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

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

    Output

    -4
    0
    

    Integers include negatives and zero, not just counting numbers.

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

    Output

    7
    7
    

    7 is an integer; "7" is text that only looks like one — Python treats them differently (you will see how in a moment).

  6. Integers can do arithmetic: add +, subtract -, multiply *. // tells how many whole groups fit, and % tells what is left over.

  7. print(5 + 3)

    Output

    8
    

    Python works out the math and prints the result.

  8. print(10 - 4)

    Output

    6
    

    - subtracts.

  9. print(6 * 7)

    Output

    42
    

    * multiplies.

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

    Output

    17
    

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

  11. print(17 // 5)

    Output

    3
    

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

  12. print(17 % 5)

    Output

    2
    

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

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

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

    Output

    27
    

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

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

    Output

    As text, the count is 5.
    

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

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

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

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

  18. import random

    import random loads Python's random toolbox — it prints nothing by itself, but the tools are now ready to use.

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

  20. random.seed(1)
  21. import random
    print(random.randint(1, 6))

    Output

    2
    

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

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

    Output

    73
    

    Change the two numbers to change the range.

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

    Output

    (sneak peek) the secret is 2
    

    Save the pick in a variable to use later — this is how the game hides its secret.

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

  25. print(7 == 7)

    Output

    True
    

    A comparison reports True or False — a boolean.

  26. print(3 < 10)
    print(10 < 3)

    Output

    True
    False
    

    < is True only when the left side is smaller.

  27. print(5 != 4)
    print(5 != 5)

    Output

    True
    False
    

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

  28. print(5 > 2)
    print(2 > 5)

    Output

    True
    False
    

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

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

    Output

    False
    True
    

    You can compare saved numbers — exactly what the game needs to judge a guess.

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

    Output

    True
    

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

  31. Lesson 3: Make a Choice

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

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

    Output

    Too low!
    

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

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

    Output

    (done checking)
    

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

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

    Output

    Keep trying.
    

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

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

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

    Output

    Too low!
    

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

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

    Output

    Warm
    

    Python takes the FIRST branch whose test is True, then stops checking the rest.

  38. secret = 37
    guess = 52
    
    if guess > secret:
        print("Too high!")
    elif guess < secret:
        print("Too low!")
    else:
        print("You found it!")

    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.

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

    Put it together and the detective gives a verdict for one real guess.

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

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

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

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

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

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

    Put an if inside the loop to give a smarter hint on every guess.

  44. 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.
    
  45. 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.

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

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

  47. 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?

  48. 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!")
  49. The traceback points to the comparison: input() made text, but secret is an integer. Convert the typed guess before comparing it.

  50. 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!")
  51. Play your full game with a partner. Mark one line on paper for every guess, then swap seats and play again.

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

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

  54. guess = 3
    secret = 7
    print(guess != secret)

    Output

    True
    

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

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

    Output

    False
    

    The moment the guess matches, guess != secret is False and the loop STOPS — that match is the sentinel.

  56. 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!
    
  57. 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.

  58. 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!
    
  59. 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!.

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

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