Python 3.14 ·
✓ verified by execution on 2026-07-22
Building a Real Program
It is time to put everything you have learned together! You are going to build a classic Number Guessing Game. When building a larger program, we use program decomposition—breaking the problem down into smaller, solvable pieces.
Instead of writing everything at once, we start by getting just one part working. Let’s make sure we can convert user input to an integer properly.
python
guess = int('50')if guess == 50: print('Match')
Output
Match
Your output
The Game Logic
The core logic of our game requires comparing the player’s guess to a secret number. Before we worry about generating a random number, we can hardcode the secret. This guarantees we know the answer while we test our logic using if, elif, and else.
A game needs to keep asking for guesses until the player wins. The while statement is used for repeated execution as long as an expression is true. We can use while True to create an infinite loop, and then use a break statement to exit the loop when the game is won. The break statement breaks out of the innermost enclosing loop.
Let’s visualize how a break statement interrupts a loop:
Now we combine our loop, our feedback logic, and our input() function. If the prompt argument is present in input(), it is written to standard output.
Try running the complete game right here! The secret number is currently hardcoded to 42.
python
secret = 42attempts = 0print("Welcome to the Number Guessing Game! The secret is 42.")while True: attempts += 1 guess_str = input("Enter your guess: ") guess = int(guess_str) if guess < secret: print('Too low') elif guess > secret: print('Too high') else: print(f'Correct in {attempts} attempts!') break
This example raises an error (on purpose)
EOFError
Your output
Check yourself
Why should you build a game with a hardcoded secret number first, before adding randomness?
Reveal answer
It allows you to decompose the program and test the core logic reliably. — Program decomposition means breaking a problem down. Testing logic with a known secret makes debugging much easier.
What does the `break` statement do?
Reveal answer
It breaks out of the innermost enclosing for or while loop. — The break statement instantly exits the loop it is placed in, which is perfect for ending a game when the user wins.
What happens if a user types text when input() expects a number to be converted to an integer?
Reveal answer
The int() function raises a ValueError. — int() cannot parse arbitrary text into a number and will raise a ValueError if it doesn't represent a valid number.
Challenges
Challenge 1 +50 XP
Write a while loop that increments the variable `count` until it reaches 5, then breaks and prints `count`.
python
Test 1 — expects "5\n"
Need a hint? (−25% XP)
Use a while True loop with an if statement checking if count is 5, and a break statement.