Lesson 10 of 30
In progress
Build a number guessing game
Put if, while, break and the random module together in a small game with hints and an attempt limit.
A game is a good first project because it forces you to combine decisions and loops, and it gives immediate feedback when you get it wrong. It is also small enough to finish in one sitting.
What you will learn
- Generate a random number with a fixed seed for testing.
- Combine
while,if,breakand counters in one program. - Make hints that help rather than repeat the guess.
Plan before you type
Write the rules in plain words first:
- Pick a secret number between 1 and 20.
- Give the player five attempts.
- On each attempt, read a guess and compare it with the secret.
- Say "higher" or "lower", and stop on a correct guess.
- Report the result and the number of attempts used.
That list becomes the structure of the program. Each line is either a loop, a decision, or a counter. Keep the plan beside the code as comments while you build, then delete the comments once the code says the same thing plainly; comments that repeat the code are noise, comments that explain a choice are useful.
Pick a secret number
The random module generates numbers that are hard to predict. For learning and testing, random.seed() makes the sequence repeatable, so your program behaves the same on every run.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
random.seed(7)
secret = random.randint(1, 20)
print("Secret for this test run:", secret)
Press Run to see the output.
randint(1, 20) includes both ends, unlike range. Remove the seed line and the print when you use the game for real.
Compare, hint and stop
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
random.seed(4)
secret = random.randint(1, 20)
attempts = 0
limit = 5
won = False
while attempts < limit:
guess = int(input("Guess a number from 1 to 20: "))
attempts += 1
if guess == secret:
won = True
break
elif guess < secret:
print("Higher")
else:
print("Lower")
if won:
print(f"Correct in {attempts} attempts")
else:
print(f"Out of attempts. The number was {secret}")
Press Run to see the output.
The won flag is what lets the program tell the two ways out of the loop apart. Without it, a player who used all five attempts would still reach the success message, because the loop ended either way. That is a logical bug, not a syntax error, and flags are the usual fix.
Make the hints honest
A hint that only repeats the guess teaches nothing, so always say which direction to move. "Higher" when the guess was too low is the kind of bug that makes a game feel broken. Read your comparisons aloud: if guess < secret, the secret is larger, so the hint is "Higher". The player should raise their next guess, not lower it.
Test the edges
Try a guess of 1, a guess of 20, a guess that is not a number, and a guess outside the range. The last two crash the program. Module 4 fixes that with try and except, and here is the shape of the fix so you can see where it is going:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
random.seed(4)
secret = random.randint(1, 20)
try:
guess = int(input("Guess: "))
print("You guessed", guess)
except ValueError:
print("That was not a whole number")
Press Run to see the output.
Test with a scripted game
A fixed seed plus a scripted series of guesses gives you a repeatable test: guess 1, then 20, then the secret. Run it twice and confirm both runs behave identically. When the seeded run passes, remove the seed and play once by hand. That order matters, because a random game that fails is hard to reproduce and therefore hard to fix.
Test the losing path deliberately. Play badly on purpose, five times, and check that the reveal message is correct and that the game does not claim a win.
A common mistake is resetting attempts inside the loop, which makes the limit meaningless. Initialise counters before the loop and change them only inside.
Extend the game so that after a win it asks "Play again? (y/n)" and restarts with a new secret number if the answer is y. Keep the attempt count per game.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
random.seed(11)
playing = True
while playing:
secret = random.randint(1, 20)
attempts = 0
won = False
while attempts < 5:
guess = int(input("Guess 1-20: "))
attempts += 1
if guess == secret:
won = True
break
print("Higher" if guess < secret else "Lower")
print(f"You got it in {attempts}." if won else f"The number was {secret}.")
playing = input("Play again? (y/n): ").strip().lower() == "y"
Press Run to see the output.
The outer loop holds the session and the inner loop holds one game. Counters are reset at the start of each game, not inside the guess loop.
Recap
- A short written plan turns into branching, looping and counting code.
- A
wonflag distinguishes running out of attempts from winning. - Test the losing path and the edges, not just the happy path.
You have finished the control-flow module. Next, you will store groups of values in lists and stop writing one variable per item.
Why use random.seed() in a game?
Why does my game crash when I type a letter?
”How
Progress is saved in this browser only. No account, no email.