A guessing game is a compact project that exercises input, conditions, loops, and random numbers. You will build it incrementally, then test the edge cases.
What you will build#
The program chooses a secret number between 1 and 100. The player has a limited number of attempts. After each guess, the program reports whether the guess is too low, too high, or correct. The game ends with a win or a loss message.
Requirements#
- Choose a random integer from 1 to 100 with
random.randint(1, 100). - Allow at most 7 guesses.
- Print
Too low,Too high, orCorrectafter each guess. - Reject values outside 1–100 without consuming an attempt? Decide and document your choice.
- After the game, print the secret number if the player lost.
- Validate input with
try/except ValueErrorinstead of crashing.
Plan the program#
Write the loop in plain language before coding:
- Set
secretandattempts_left. - While attempts remain:
- Read a guess.
- Validate it.
- Compare it with the secret.
- Stop on a correct guess.
- Print the result.
Keep input and game logic separate where possible. A function such as read_guess() can return a valid integer or None, leaving the loop focused on the game.
Starter code#
import random
secret = random.randint(1, 100)
max_attempts = 7
attempts = 0
print("Guess a number between 1 and 100.")
print(f"You have {max_attempts} attempts.")
while attempts < max_attempts:
text = input()
attempts += 1
try:
guess = int(text)
except ValueError:
print("Enter a whole number.")
continue
if guess < 1 or guess > 100:
print("Stay between 1 and 100.")
continue
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
else:
print(f"Correct in {attempts} attempts!")
break
else:
print(f"Out of attempts. The number was {secret}.")Make it your own#
- Change the range and the attempt limit.
- Print how many attempts remain after each guess.
- Use a
while Trueloop with an explicitbreakinstead of the loop condition. - Track previous guesses in a list and reject duplicates with a helpful message.
- Provide a difficulty menu that sets the range and attempts before the game starts.
Testing checklist#
Test these cases with the Input panel:
| Scenario | Input | Expected behaviour |
| --- | --- | --- |
| Correct first guess | The secret value | Correct in 1 attempts! |
| Too low then correct | A lower value, then the secret | Too low then success |
| Non-number | abc | Validation message, run continues |
| Out of range | 0 or 101 | Range message, run continues |
| All attempts used | Seven wrong values | Loss message with the secret |
Because ILoveCompiler supplies all input before the run, the secret is chosen fresh each run. Use the printed hints to adapt your next guess, or temporarily print the secret while testing.
Stretch goals#
Add a score based on attempts remaining, keep a high-score table in a dictionary for the current session, or allow the player to choose the maximum number. Keep each addition small and test it before moving on.
