Problem 3
Perfect, this is Problem 3: Number Guessing Game.
This problem is different from BMI and grade because here the main ideas are:
import random- function
- difficulty choice
- random number generation
whileloop- limited attempts
try / except- validating integer guesses
- validating range
- comparing numbers
break/continue
Problem 3 — Perfect Exam Solution
This is the clean version I would write in the exam.
# Task 3: Number Guessing Game
import random
def guess():
while True:
difficulty = input("Choose difficulty: easy or hard: ").lower()
if difficulty == "easy":
max_number = 50
attempts = 10
break
elif difficulty == "hard":
max_number = 100
attempts = 7
break
else:
print("Invalid difficulty. Please choose easy or hard.")
secret_number = random.randint(1, max_number)
print(f"I chose a number between 1 and {max_number}.")
while attempts > 0:
try:
user_guess = int(input("Enter your guess: "))
if user_guess < 1 or user_guess > max_number:
print(f"Invalid guess. Enter a number between 1 and {max_number}.")
continue
attempts -= 1
if user_guess == secret_number:
print("Correct!")
return
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
print(f"Guesses remaining: {attempts}")
except ValueError:
print("Please enter an integer number.")
print(f"You ran out of guesses. The number was {secret_number}.")
guess()
This is a very good exam answer because it satisfies every bullet:
| Requirement | Code part |
|---|---|
Create function guess() | def guess(): |
| Easy difficulty: 1–50, 10 guesses | max_number = 50, attempts = 10 |
| Hard difficulty: 1–100, 7 guesses | max_number = 100, attempts = 7 |
| Random number | random.randint(1, max_number) |
| Too high / too low / correct | if user_guess == secret_number, elif user_guess > secret_number, else |
| Guesses remaining | print(f"Guesses remaining: {attempts}") |
| Reveal number if attempts finish | final print(...) after loop |
| Reject non-integers | try / except ValueError |
| Reject out-of-range guesses | if user_guess < 1 or user_guess > max_number |
Example run
User chooses easy:
Choose difficulty: easy or hard: easy
I chose a number between 1 and 50.
Enter your guess: 25
Too low!
Guesses remaining: 9
Enter your guess: 40
Too high!
Guesses remaining: 8
Enter your guess: 35
Correct!
If user runs out:
You ran out of guesses. The number was 17.
Step-by-step explanation
1. Import random
At the top we write:
import random
This allows us to use Python’s random module.
Without this line, this will not work:
random.randint(1, max_number)
Python would say:
NameError: name 'random' is not defined
So for any random-number problem, remember:
import random
2. Create the function
The task says:
So we write:
def guess():
Everything inside the function must be indented:
def guess():
print("Game starts")
At the end, we call the function:
guess()
Without calling it, the game will not start.
3. Difficulty choice
The task says:
We write:
difficulty = input("Choose difficulty: easy or hard: ").lower()
The .lower() is useful because it converts the input to lowercase.
So these all become "easy":
Easy
EASY
easy
EaSy
That makes your code safer.
Then:
if difficulty == "easy":
max_number = 50
attempts = 10
break
elif difficulty == "hard":
max_number = 100
attempts = 7
break
else:
print("Invalid difficulty. Please choose easy or hard.")
Meaning:
- If easy, number range is 1 to 50 and user has 10 tries.
- If hard, number range is 1 to 100 and user has 7 tries.
- If user types something else, ask again.
Why use while True for difficulty?
This part:
while True:
difficulty = input("Choose difficulty: easy or hard: ").lower()
if difficulty == "easy":
max_number = 50
attempts = 10
break
elif difficulty == "hard":
max_number = 100
attempts = 7
break
else:
print("Invalid difficulty.")
means:
“Keep asking until the user gives a correct difficulty.”
If user writes:
medium
the code prints:
Invalid difficulty.
and asks again.
When user finally writes:
easy
then we set values and use:
break
to stop the difficulty loop.
4. Generate random number
After we know the difficulty, we create the secret number:
secret_number = random.randint(1, max_number)
If difficulty is easy:
max_number = 50
So this becomes:
secret_number = random.randint(1, 50)
If difficulty is hard:
max_number = 100
So this becomes:
secret_number = random.randint(1, 100)
Important:
random.randint(1, 50)
includes both 1 and 50.
So possible numbers are:
1, 2, 3, ..., 49, 50
5. Main guessing loop
This is the main game:
while attempts > 0:
It means:
“As long as the user still has attempts, keep asking for guesses.”
Example:
attempts = 10
The loop continues while attempts are:
10, 9, 8, 7, ..., 1
When attempts becomes:
0
the loop stops.
Then this line runs:
print(f"You ran out of guesses. The number was {secret_number}.")
6. Input validation with try / except
Inside the loop:
try:
user_guess = int(input("Enter your guess: "))
We use int() because guesses must be whole numbers.
If user types:
25
then:
user_guess = 25
But if user types:
hello
Python cannot do:
int("hello")
So it gives ValueError.
That is why we write:
except ValueError:
print("Please enter an integer number.")
This prevents the program from crashing.
7. Reject out-of-range guesses
The task says:
For easy mode, guesses must be between 1 and 50.
For hard mode, guesses must be between 1 and 100.
Since we use max_number, we can write one condition for both:
if user_guess < 1 or user_guess > max_number:
print(f"Invalid guess. Enter a number between 1 and {max_number}.")
continue
Meaning:
- If guess is smaller than 1, reject.
- If guess is bigger than max number, reject.
Example in easy mode:
max_number = 50
If user guesses:
80
then:
user_guess > max_number
is true.
So print:
Invalid guess. Enter a number between 1 and 50.
Then:
continue
means skip the rest of this loop and ask again.
Very important: invalid guesses should not count
In our code, this comes before reducing attempts:
if user_guess < 1 or user_guess > max_number:
print("Invalid guess.")
continue
attempts -= 1
So if the guess is invalid, Python reaches continue and does not run:
attempts -= 1
That means invalid guesses do not reduce attempts.
This is usually the best interpretation of “reject invalid input.”
8. Count attempts
After the guess is valid, we count it:
attempts -= 1
This means:
attempts = attempts - 1
Example:
attempts = 10
After one valid guess:
attempts = 9
After another valid guess:
attempts = 8
So:
attempts -= 1
is just a short way to subtract 1.
9. Compare guess with secret number
This part decides what message to print:
if user_guess == secret_number:
print("Correct!")
return
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
Meaning:
If guess equals secret number
if user_guess == secret_number:
Then:
print("Correct!")
return
The game ends.
Here return exits the function completely.
If guess is bigger than secret number
elif user_guess > secret_number:
Then print:
Too high!
Example:
secret_number = 30
user_guess = 45
45 is too high.
Otherwise guess is smaller
else:
print("Too low!")
Example:
secret_number = 30
user_guess = 20
20 is too low.
10. Show guesses remaining
After each valid wrong guess:
print(f"Guesses remaining: {attempts}")
This uses an f-string.
Example:
attempts = 8
Then:
print(f"Guesses remaining: {attempts}")
prints:
Guesses remaining: 8
What is an f-string?
This:
print(f"Guesses remaining: {attempts}")
means Python puts the value of attempts inside the text.
Example:
attempts = 5
Then:
f"Guesses remaining: {attempts}"
becomes:
Guesses remaining: 5
You can also write it without f-string:
print("Guesses remaining:", attempts)
Both are correct.
For exam, either is fine.
What does return do here?
In this code:
if user_guess == secret_number:
print("Correct!")
return
return stops the whole function.
So if user guesses correctly, the game ends immediately.
Without return, the loop might continue or the “ran out of guesses” message might appear incorrectly.
Alternative:
break
You could also use break, but then after the loop you must be careful not to print the losing message.
For this problem, return is clean and simple.
What does continue do?
This line:
continue
means:
“Skip the rest of this loop and go back to the top.”
In this part:
if user_guess < 1 or user_guess > max_number:
print("Invalid guess.")
continue
attempts -= 1
If guess is invalid, Python prints the message and goes back to ask again.
It does not subtract attempts.
So:
continue
is useful when invalid input should be rejected.
What does break do?
We use break in the difficulty loop:
if difficulty == "easy":
max_number = 50
attempts = 10
break
break means:
“Stop this loop.”
So after valid difficulty is chosen, we leave the difficulty loop and start the game.
Full beginner-friendly version without f-strings
If f-strings confuse you, this version is also correct:
# Task 3: Number Guessing Game
import random
def guess():
while True:
difficulty = input("Choose difficulty: easy or hard: ").lower()
if difficulty == "easy":
max_number = 50
attempts = 10
break
elif difficulty == "hard":
max_number = 100
attempts = 7
break
else:
print("Invalid difficulty. Please choose easy or hard.")
secret_number = random.randint(1, max_number)
print("I chose a number between 1 and", max_number)
while attempts > 0:
try:
user_guess = int(input("Enter your guess: "))
if user_guess < 1 or user_guess > max_number:
print("Invalid guess. Enter a number between 1 and", max_number)
continue
attempts = attempts - 1
if user_guess == secret_number:
print("Correct!")
return
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
print("Guesses remaining:", attempts)
except ValueError:
print("Please enter an integer number.")
print("You ran out of guesses. The number was", secret_number)
guess()
This is a little simpler visually.
Shorter version if you panic in exam
This version is less perfect because difficulty validation is simpler, but it is still understandable.
import random
def guess():
difficulty = input("Choose difficulty: easy or hard: ").lower()
if difficulty == "easy":
max_number = 50
attempts = 10
elif difficulty == "hard":
max_number = 100
attempts = 7
else:
print("Invalid difficulty")
return
secret_number = random.randint(1, max_number)
while attempts > 0:
try:
user_guess = int(input("Enter your guess: "))
if user_guess < 1 or user_guess > max_number:
print("Out of range")
continue
attempts -= 1
if user_guess == secret_number:
print("Correct!")
return
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
print("Guesses remaining:", attempts)
except ValueError:
print("Enter an integer.")
print("You lost. The number was", secret_number)
guess()
This is easier to memorize. The first version is better, but this one is okay if you are under time pressure.
Code pattern to memorize
For number guessing games, memorize this skeleton:
import random
def guess():
secret = random.randint(1, 100)
attempts = 7
while attempts > 0:
try:
guess = int(input("Enter guess: "))
attempts -= 1
if guess == secret:
print("Correct")
return
elif guess > secret:
print("Too high")
else:
print("Too low")
print("Attempts left:", attempts)
except ValueError:
print("Enter integer")
print("The number was", secret)
guess()
Then add difficulty and range validation.
Main theory from this problem
1. random.randint(a, b)
random.randint(1, 50)
gives a random integer from 1 to 50.
Important: both sides are included.
So:
random.randint(1, 3)
can give:
1, 2, or 3
Not 0. Not 4.
2. while attempts > 0
This loop is perfect for limited tries.
while attempts > 0:
means keep looping while the user still has guesses.
Every valid guess:
attempts -= 1
When attempts becomes 0, the loop stops.
3. try / except
Use this when the user must enter a number.
try:
guess = int(input("Enter guess: "))
except ValueError:
print("Enter an integer")
This catches inputs like:
hello
12.5
abc
Since the task says reject non-integers, using int() is correct.
4. if / elif / else
Used for comparing guess and secret number:
if user_guess == secret_number:
print("Correct!")
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
This is the heart of the game.
5. return
Used to stop the game when the answer is correct:
return
It exits the function completely.
6. continue
Used to reject bad guesses without counting them:
continue
Example:
if user_guess < 1 or user_guess > max_number:
print("Invalid guess")
continue
So the program goes back to ask again.
7. break
Used to stop a loop when something valid happens:
break
In our code, we use it after valid difficulty is selected.
Common mistakes in this problem
Mistake 1: Forgetting to import random
Wrong:
secret_number = random.randint(1, 50)
without:
import random
Correct:
import random
secret_number = random.randint(1, 50)
Mistake 2: Using random.randint() wrongly
Wrong:
secret_number = random.randint(50)
Correct:
secret_number = random.randint(1, 50)
randint() needs two numbers:
random.randint(start, end)
Mistake 3: Not converting input to int
Wrong:
user_guess = input("Enter guess: ")
Then this compares string to number:
if user_guess > secret_number:
That causes problems.
Correct:
user_guess = int(input("Enter guess: "))
Mistake 4: Counting invalid guesses
Bad order:
attempts -= 1
if user_guess < 1 or user_guess > max_number:
print("Invalid guess")
continue
This subtracts attempt even when guess is invalid.
Better order:
if user_guess < 1 or user_guess > max_number:
print("Invalid guess")
continue
attempts -= 1
Invalid guess does not count.
Mistake 5: Forgetting to stop after correct answer
Wrong:
if user_guess == secret_number:
print("Correct!")
But no return or break.
Correct:
if user_guess == secret_number:
print("Correct!")
return
Mistake 6: Wrong comparison signs
Correct:
if user_guess == secret_number:
print("Correct!")
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
Do not confuse:
=
and:
==
This is assignment:
x = 5
This is comparison:
x == 5
For checking equality, always use:
==
Mistake 7: Difficulty case problem
If you write:
difficulty = input("Choose difficulty: ")
if difficulty == "easy":
and user types:
Easy
then it will not match.
Better:
difficulty = input("Choose difficulty: ").lower()
Now "Easy" becomes "easy".
Should invalid input reduce attempts?
Usually no.
Because the task says:
Reject means do not accept it as a guess.
So this should not reduce attempts:
hello
-5
200
Only valid guesses should reduce attempts.
That is why we write:
if user_guess < 1 or user_guess > max_number:
print("Invalid guess")
continue
attempts -= 1
Similar problems they can ask in the make-up exam
This problem tests loops, random, validation, and attempts. The make-up may not be exactly “number guessing game,” but it can be very close.
Similar Problem 1: Number guessing game with 3 difficulty levels
They could add medium:
Easy: 1–50, 10 guesses
Medium: 1–75, 8 guesses
Hard: 1–100, 7 guesses
Solution:
import random
def guess():
while True:
difficulty = input("Choose easy, medium, or hard: ").lower()
if difficulty == "easy":
max_number = 50
attempts = 10
break
elif difficulty == "medium":
max_number = 75
attempts = 8
break
elif difficulty == "hard":
max_number = 100
attempts = 7
break
else:
print("Invalid difficulty.")
secret_number = random.randint(1, max_number)
while attempts > 0:
try:
user_guess = int(input("Enter guess: "))
if user_guess < 1 or user_guess > max_number:
print("Out of range.")
continue
attempts -= 1
if user_guess == secret_number:
print("Correct!")
return
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
print("Guesses remaining:", attempts)
except ValueError:
print("Enter an integer.")
print("You lost. Number was", secret_number)
guess()
Only difference: more elif.
Similar Problem 2: Guess dice roll
They could ask:
Code:
import random
def dice_guess():
secret_number = random.randint(1, 6)
attempts = 3
while attempts > 0:
try:
user_guess = int(input("Guess dice number from 1 to 6: "))
if user_guess < 1 or user_guess > 6:
print("Enter a number between 1 and 6.")
continue
attempts -= 1
if user_guess == secret_number:
print("Correct!")
return
else:
print("Wrong!")
print("Guesses remaining:", attempts)
except ValueError:
print("Enter an integer.")
print("You lost. The number was", secret_number)
dice_guess()
Same skeleton, just smaller range and attempts.
Similar Problem 3: PIN guessing game
They could ask:
Code:
import random
def pin_game():
pin = random.randint(1000, 9999)
attempts = 5
while attempts > 0:
try:
guess = int(input("Enter 4-digit PIN: "))
if guess < 1000 or guess > 9999:
print("PIN must be 4 digits.")
continue
attempts -= 1
if guess == pin:
print("Correct PIN!")
return
else:
print("Wrong PIN.")
print("Attempts left:", attempts)
except ValueError:
print("Enter only integers.")
print("You failed. The PIN was", pin)
pin_game()
Same pattern:
random.randint()
while attempts > 0
try / except
range check
attempts -= 1
if correct return
Similar Problem 4: Random math quiz
They could ask:
Code:
import random
def math_quiz():
a = random.randint(1, 20)
b = random.randint(1, 20)
correct_answer = a + b
attempts = 3
print("What is", a, "+", b, "?")
while attempts > 0:
try:
answer = int(input("Enter answer: "))
attempts -= 1
if answer == correct_answer:
print("Correct!")
return
else:
print("Wrong.")
print("Attempts left:", attempts)
except ValueError:
print("Enter an integer.")
print("You lost. Correct answer was", correct_answer)
math_quiz()
This is very similar but instead of comparing too high/too low, you compare answer with correct answer.
Similar Problem 5: Guess a random word
They could ask:
Code:
import random
def word_guess():
words = ["apple", "banana", "cherry"]
secret_word = random.choice(words)
attempts = 3
while attempts > 0:
guess = input("Guess the word: ").lower()
attempts -= 1
if guess == secret_word:
print("Correct!")
return
else:
print("Wrong!")
print("Attempts left:", attempts)
print("You lost. The word was", secret_word)
word_guess()
New thing:
random.choice(words)
This chooses one random item from a list.
For numbers, use:
random.randint(1, 100)
For list items, use:
random.choice(list_name)
Important mini-cheat sheet
Random number
import random
number = random.randint(1, 100)
Random item from list
item = random.choice(["apple", "banana", "cherry"])
Limited attempts
attempts = 5
while attempts > 0:
attempts -= 1
Validate integer
try:
guess = int(input("Enter guess: "))
except ValueError:
print("Enter an integer.")
Validate range
if guess < 1 or guess > 100:
print("Out of range.")
continue
Compare guess
if guess == secret:
print("Correct")
elif guess > secret:
print("Too high")
else:
print("Too low")
Stop after correct answer
return
Skip invalid input
continue
Final version to memorize
Practice this one. It covers everything in the task.
# Task 3: Number Guessing Game
import random
def guess():
while True:
difficulty = input("Choose difficulty: easy or hard: ").lower()
if difficulty == "easy":
max_number = 50
attempts = 10
break
elif difficulty == "hard":
max_number = 100
attempts = 7
break
else:
print("Invalid difficulty. Please choose easy or hard.")
secret_number = random.randint(1, max_number)
print("I chose a number between 1 and", max_number)
while attempts > 0:
try:
user_guess = int(input("Enter your guess: "))
if user_guess < 1 or user_guess > max_number:
print("Invalid guess. Enter a number between 1 and", max_number)
continue
attempts -= 1
if user_guess == secret_number:
print("Correct!")
return
elif user_guess > secret_number:
print("Too high!")
else:
print("Too low!")
print("Guesses remaining:", attempts)
except ValueError:
print("Please enter an integer number.")
print("You ran out of guesses. The number was", secret_number)
guess()
The main recipe is:
import random
secret = random.randint(1, max_number)
while attempts > 0:
guess = int(input(...))
attempts -= 1
if guess == secret:
return
elif guess > secret:
print("Too high")
else:
print("Too low")
This problem is basically: random number + while loop + attempts + validation + comparison.
Posted May 12, 2026, 2:58 PM UTC