Codzy

Project 2: the mystery number game

The classic game: the computer picks a number between 1 and 100, the player guesses, the game answers "higher" or "lower". To be able to test the game automatically, we separate the logic (play(secret, guesses)) from the input: guesses arrive as a list instead of input().

A good game helps the player by showing the remaining range. And there's a perfect strategy: binary search. By always guessing the middle of the range, you halve the possibilities each time: 7 tries are always enough for 100 numbers (2⁷ = 128). random.seed makes randomness reproducible during tests.

import random

random.seed(7)  # same "random" number every run, handy for testing
secret = random.randint(1, 100)
for guess in [50, 75, 62]:
    if guess < secret:
        print(guess, "-> higher")
    elif guess > secret:
        print(guess, "-> lower")
    else:
        print(guess, "-> found!")

Start the lesson