Python 5.3 : Exercise : condition
In this exercise we focus on conditions. The idea is to compare a number entered by the user with the magic number chosen earlier and display three possible outcomes on the screen: "the magic number is bigger", "the magic number is smaller", or "bravo, you have won". For now the user only gets a single attempt to find the value. Try it on your own first, then have a look at the correction below.
Chaining if, elif and else
We start with the winning case: if the number entered is equal to the magic number, we print the success message. Otherwise we test whether the magic number is greater than the user's guess with elif, in which case the magic number is bigger. The remaining situation is handled by a final else that prints the opposite message.
if number == magic_number:
print("Bravo, you have won")
elif magic_number > number:
print("The magic number is bigger")
else:
print("The magic number is smaller")
When we run the program a few times we can validate the three branches: entering exactly the magic number triggers the bravo message, entering a smaller value tells us the magic number is bigger, and entering a larger value tells us it is smaller. Everything behaves as expected. In the next video we will reuse this exact comparison inside a loop so the user can have several attempts.
Summary
In this exercise, learners implement conditional logic to build a number-guessing game that compares user input against a magic number. The program evaluates three outcomes: exact match (success), number too small, or number too large. This hands-on practice reinforces if/elif/else structures in Python through a simple but practical application.
Key points
- Use if statements to test equality and compare numbers against a target value
- Chain multiple conditions with elif to handle different comparison outcomes
- Provide meaningful feedback messages for each conditional branch (correct, too small, too large)
- Understand that the user has only one attempt to guess the magic number
- Apply comparison operators: ==, >, < to evaluate numeric relationships
FAQ
What is the magic number and how do we define it?
The magic number is a predetermined target value set in the program that the user must guess. It remains hidden from the user, and they must find it by making a single guess that is then compared using conditional statements.
How many conditional branches do we need for this exercise?
Three branches are required: an if statement to check for exact match (equality), an elif to handle when the guess is smaller than the magic number, and an else to handle when the guess is larger.
Why is one attempt sufficient for this exercise?
The single-attempt constraint simplifies the logic for beginners learning conditionals—it eliminates the need for loops and focuses attention on how if/elif/else structures handle different comparison outcomes.