← Intro to programming with Python

Mini project: number guessing game

Keep asking until the player finds the secret number.

Start this lesson

A guessing game is a while loop at heart: keep asking WHILE the guess is wrong. Each time round, read a guess, give a hint (too high or too low), and count the tries. When the guess matches, the loop ends and you congratulate the player. (Here the secret number is fixed so the game can be tested; you will make it random in the modules unit.)

secret = 7
guess = 0
while guess != secret:
    guess = int(input("Guess: "))
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
print("You got it!")

guess starts at 0 so the loop runs at least once. When the player types 7, no hint shows, the condition is False, and the loop ends.

Common mistake: asking for the guess BEFORE the loop only. Then the guess never changes and the loop runs forever. The input() must be inside the loop.