Number Guessing Game
🎯 Number Guessing Game
random module — all from Course 1.
🎮 What We're Building
A simple, genuinely fun command-line game: the program secretly picks a random number between 1 and 100, the player guesses repeatedly, and after each guess the program says "too high," "too low," or "correct" — ending with how many attempts it took.
Step 1: Picking a Random Number
random.randint(1, 100) reuses the exact function from Course 1, Chapter 9's own dice-roller challenge — inclusive on both ends, so it can return anything from 1 through 100.
Step 2: The Guessing Loop
An infinite while True loop (Course 1, Chapter 4) — the game keeps asking for guesses until something inside the loop explicitly breaks out of it. input() always returns a string, so int(...) wraps it immediately to get a real number to compare.
Step 3: Giving Feedback
Plain if/elif/else comparisons (Course 1, Chapter 3) — the break only fires on a correct guess, exiting the while True loop from Step 2 at exactly that point.
Step 4: Counting Attempts & Ending the Game
attempts is the same running-total accumulator pattern from Course 1, Chapter 4 — initialized to 0 outside the loop, incremented by 1 on every pass through it, then read once the loop finally ends.
🏁 The Complete Game
That's a complete, playable game in 15 lines — every piece is something already covered in Course 1, combined into something genuinely fun to run rather than a standalone exercise.
Typing "forty" instead of a number raises a ValueError from int(...), crashing the whole program — this version doesn't validate input yet. Course 2, Chapter 3's try/except ValueError is exactly the fix, and it's one of this chapter's own suggested extensions below.
random.randint()
Picks the secret number, inclusive on both ends.
while True + break
Loops until the correct guess is made, then exits.
if/elif/else
Compares the guess to the secret number and gives a hint.
Accumulator pattern
attempts counts guesses across every pass through the loop.
Try these on your own — no solutions provided, just like a real side project:
- Wrap the
int(input(...))line in atry/except ValueError(Course 2, Chapter 3) so a non-numeric guess prints a friendly message and asks again, instead of crashing. - Add a difficulty selector at the start (easy = 1-50, hard = 1-500), changing the
random.randint()range based on the player's choice. - After the player wins, ask if they want to play again — wrap the entire game in an outer loop, reusing the loop-inside-a-loop pattern from Course 2, Chapter 5's nested comprehensions (conceptually, not literally a comprehension here).
- Give up after 10 attempts instead of looping forever — track
attemptsagainst a limit andbreakwith a "you lose" message if it's exceeded.
🎯 What's Next
Next chapter: Simple Calculator — functions and basic error handling.