Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

The Guessing Game: Your First Game Logic

10 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 1 of 5 · View course roadmap
Step 1

Learn the idea

Almost every game is the same three-beat loop: the player acts, the game checks, the game responds. You already know enough Python to build that:

  • if guess < secret: — the check
  • print("Too low!") — the response
  • A for loop — one turn per guess

Real games read the player's input live; here we simulate a player with a list of guesses so the game runs the same way every time. Everything else — the logic — is identical to the real thing.

Notice the order matters: check too low, then too high, and let else handle the win. When you can predict which branch runs for any guess, you think like a game programmer.

Where you'll use this

The check-and-respond loop you just built is the event loop inside every interactive program: games, chat apps, even web servers do exactly this — receive input, branch, respond, repeat.

Common mistakes

  • Getting the branch order wrong so a case can never be reached — test all three paths (low, high, equal).
  • Using = where you mean == inside a condition — assignment vs comparison.
  • Forgetting to indent the if/elif/else inside the for loop, so only the last guess is checked.

Pro tip

When logic misbehaves, print the state each turn: print(guess, 'vs', secret). Watching values flow through a loop fixes most bugs faster than staring at the code.

Step 2

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +25 XP

Blank · autosaved

The secret number is 7. A player guesses 3, then 9, then 7. Loop over the guesses and print Too low!, Too high! or You got it! for each one.

Target output
Too low!
Too high!
You got it!
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. In if guess < secret: ... elif guess > secret: ... else: ..., when does else run?
2. Why simulate the player with a list of guesses here?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path