▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Mini project: number-guessing game
A game with random numbers, hints and a score.
🎬 Video version coming soon — read it now
Let's build a real game using everything from this course: comparisons, if/elif/else, while loops, break and counting.
How the game works
- The computer picks a secret number from 1 to 100.
- You guess. It says "higher" or "lower".
- You have 7 tries. Fewer guesses means a better score.
The code
Two new things
import randomloads Python's random module.random.randint(1, 100)picks a whole number from 1 to 100, including both ends.while ... else: theelseblock runs only if the loop finished without abreak. Here that means you used up all your tries.
Why 7 tries is fair
Always guess the middle of the range that's left: 50, then 25 or 75, and so on. Each guess halves the possibilities, and 2 to the power 7 is 128, which is more than 100. This idea is called binary search, and it's one of the most important ideas in computer science.
Challenges
- Play again: wrap the game in a
while Trueloop and ask "Play again? (y/n)". - Difficulty levels: easy (1 to 50, 10 tries), hard (1 to 500, 9 tries).
- Track the best score across rounds.
- Reverse it: you pick the number and the computer guesses using binary search.
- Don't crash on text input. Hint:
guess_text.isdigit().
What you learned in this course
- Booleans and comparisons; if, elif and else
- and, or, not; for loops with range, and while loops
- break, continue, nested loops and patterns
- Tracing code, with and without AI
Next course: Lists, Dicts & Data. You'll learn to store hundreds of values at once and build a student marks report.
In one line
You built a complete game with random numbers, loops and decisions, and met binary search along the way.
Share with a friend