You have three guesses to find a number. After each miss, the game tells you whether to go higher or lower. The answer is fixed at 7 so you can repeat a round with the same inputs and check exactly where it ends.
Save the program as guess.py. Each time you see Guess and an attempt number, type an integer and press Enter. input() returns the line as text, and int() converts integer text into a number the game can compare with secret.[1]
secret = 7limit = 3won = Falseprint("You have", limit, "guesses.")for attempt in range(1, limit + 1): print("Guess", attempt) guess = int(input()) if guess == secret: print("You got it!") won = True break elif guess < secret: print("Too low.") else: print("Too high.")if not won: print("Out of guesses. The number was", secret)
Run it from the folder where you saved the file. Both rounds below were tested with Python 3.14.9 on Linux. The output blocks show what the script prints; your terminal may also echo what you type.
python3 guess.py
Enter 4, 9 and 7 on separate lines:
You have 3 guesses.Guess 1Too low.Guess 2Too high.Guess 3You got it!
Start a fresh round with the same command. Enter 4, 9 and 6:
You have 3 guesses.Guess 1Too low.Guess 2Too high.Guess 3Too low.Out of guesses. The number was 7

The if and elif conditions are checked in order; the first true condition runs its branch, and else runs when neither is true.[3] With 4, the equality check fails and 4 < 7 is true. With 9, both checks fail. On a hit, the game sets won to True before it reaches break. break ends the loop as soon as it runs.[2] The final if sits outside the loop. It reveals the number only if won is still False.
Leave room for the final guess
range excludes its stop value.[2] If you write range(1, limit), the game stops after two misses even though it announces three guesses. The + 1 gives guess 3 its turn. Typing seven instead of 7 stops the program with ValueError; this version expects integer input.
Your turn
Set limit to 4. Try 4, 9, 6 and 7 to check that the fourth guess can win. The next lesson uses lists and slicing to work with several values at once.