Raw data, clear context.

[
[
[

]
]
]

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]

guess.py
Python
secret = 7
limit = 3
won = False
print("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.

Run guess.py
Bash
python3 guess.py

Enter 4, 9 and 7 on separate lines:

Output
Plain text
You have 3 guesses.
Guess 1
Too low.
Guess 2
Too high.
Guess 3
You got it!

Start a fresh round with the same command. Enter 4, 9 and 6:

Output
Plain text
You have 3 guesses.
Guess 1
Too low.
Guess 2
Too high.
Guess 3
Too low.
Out of guesses. The number was 7
Two games with target 7. Guesses 4, 9 and 7 give Too low, Too high and You got it, then break ends the loop. Guesses 4, 9 and 6 give Too low, Too high and Too low, then the loop runs out of guesses and the game reveals 7.
Both runs reach the third guess. A hit ends the loop with break; after three misses, the line outside the loop reveals the answer.

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.

Sources

  1. Python built-in functions: input and int
  2. Python tutorial: range and break
  3. Python language reference: the if statement