Number Guessing Game 🎯
The computer picks a secret number from 1 to 100. You guess. It tells you higher or lower until you get it, then reports how many tries it took. Simple to describe, and it will teach you more than the last three lessons combined, because this time nobody is holding the pen.
📋 Build this
- Pick a secret random number from 1 to 100.
- Loop: read a guess, tell the player higher, lower, or correct.
- Count the guesses and report the total when they win.
- Handle non-numeric input without crashing.
Hints, if you want them
Try the spec cold first. Open a hint only when you are properly stuck; the struggle is where the learning is.
Hint 1: Getting a random number
`import random` then `random.randint(1, 100)` gives an inclusive random integer. Store it in a variable before the loop starts.
Hint 2: The loop shape
A
while True: loop with a break when the guess is correct is the natural fit. Read the guess with int(input(...)), compare, and print the hint.Hint 3: Not crashing on bad input
Wrap the
int(input(...)) in a try/except ValueError (Lesson 22). On a bad value, print a message and continue.The reference solution
Yours does not need to match this. There are many good ways to build any of these. Compare only after you have your own working.
Reveal the reference solution
import random
secret = random.randint(1, 100)
guesses = 0
while True:
raw = input("Guess (1-100): ")
try:
guess = int(raw)
except ValueError:
print(" Digits only, please.")
continue
guesses += 1
if guess < secret:
print(" Higher.")
elif guess > secret:
print(" Lower.")
else:
print(f"Got it in {guesses} guesses!")
breakThis one needs the network or a live secret, so it has no run button. Build it on your own machine.
Stretch goals
- Add a difficulty setting that changes the range.
- Limit the player to a maximum number of guesses.
- Add a play-again loop that keeps a running win record.