Table of Contents
Comparison operators are essential tools in Python that allow you to evaluate relationships between values. These operators—such as ==
, !=
,
>
, >=
, <
, and <=
—return boolean results (True
or False
) based on conditions. They're
most often used in decision-making structures like if
statements, loops, or filtering logic. Understanding how to compare numbers, strings, and variables is crucial
for writing programs that can react to user input or changing conditions.
In this section, you'll explore real-world tasks where you'll compare values to decide what a program should do. From checking eligibility to verifying passwords, these problems will help you understand how logic flows through condition-based code.
Before starting the tasks below, make sure you understand the following concepts:
- Comparison operators in Python
- Boolean values and logical expressions
-
Using
if
statements to control flow - Getting user input and printing output
- Understanding how to use variables to hold and compare data
Beginner-Level Practice – Comparison Operators in Python
At the beginner level, it's important to become comfortable using comparison operators in simple conditional checks. These problems will focus on direct comparisons between user
inputs and constant values, such as checking age, equality between numbers, or string matching. You'll practice using ==
, !=
, and relational operators
like >
or <=
in short, focused conditions. This will build your intuition for how Python interprets true or false conditions in real programs.
1. Are You Old Enough to Vote?
Write a program that asks the user for their age and checks whether they are eligible to vote. In most countries, the voting age is 18. If the user is 18 or older, print a message saying they can vote. Otherwise, print a message saying they are too young. This simulates a basic eligibility check found in many user-facing systems.
What this Task Teaches
This task strengthens your understanding of using comparison operators like >=
in decision-making. You will learn how to accept numerical input from users and
apply conditional logic based on thresholds. It also teaches the importance of branching the flow of execution based on different outcomes using if
and
else
statements.
- Using
>=
to check if a number meets a condition - Capturing and converting user input to integers
- Writing a basic
if
/else
block - Displaying different messages based on user data
Hints and Tips
Focus on getting the correct data type for the user's age, and make sure your comparison logic checks for the correct threshold. Think about what happens when the user is exactly 18.
- Use
input()
to ask for age and convert it to an integer - Use
if age >= 18
for eligibility check - Use
else
for the "too young" case - Print clear, user-friendly messages
Common Mistakes
Beginners often misplace operators or compare string inputs instead of integers. It’s also common to forget handling the “exactly 18” case or to write the comparison backward.
-
Forgetting to convert input: If you don’t convert the result of
input()
to an integer, your comparison won’t work as expected because you’ll be comparing a string to a number. - Wrong comparison operator: Using
>
instead of>=
excludes 18-year-olds from being eligible, which is incorrect. - Incorrect indentation: Python requires consistent indentation for
if
statements. Misaligned code leads to syntax errors. -
Comparing in the wrong direction: Writing
if 18 >= age
makes the logic harder to read and is less intuitive thanif age >= 18
. - Unclear output: Not telling the user why they’re ineligible or what the condition is can lead to confusion.
Step-by-Step Thinking
Think of this program like a form validation system. You’re asking the user for personal data and checking if they meet a requirement. That’s a typical workflow in authentication systems.
- Ask the user to input their age
- Convert the input from string to integer using
int()
- Use a comparison operator to check if the age is 18 or more
- If true, print a message saying the user can vote
- If false, print a message saying they are too young
How to Make it Harder
You can add additional checks or requirements to simulate more realistic scenarios, like checking for citizenship or whether the person is registered.
- Ask for the user’s country and allow voting only if it’s “USA” and age ≥ 18
- Require the user to enter “yes” or “no” for voter registration
- Include edge cases, like if the user enters a negative number or zero
2. Check Driving Eligibility
Write a Python program that asks the user to input their age. The program should then check if the user is old enough to legally drive. Assume the legal driving age is 18. If the user is 18 or older, print a message saying they are eligible. Otherwise, print how many years they still need to wait.
What this Task Teaches
This task introduces the use of comparison operators to evaluate user input against a defined threshold. It reinforces the use of conditionals to branch logic depending on numeric comparisons. You’ll also improve how you format output with dynamic content such as calculated age differences, making the program more helpful and responsive to the user’s data.
- Working with numeric input and conversion to
int
- Using
>=
and<
operators for condition checks - Displaying different messages based on user input
- Calculating and printing derived values (like years left)
Hints and Tips
Ask the user for their age and convert it to an integer. Then check whether it’s greater than or equal to 18. Use an else
block to handle the alternative outcome
and do a simple subtraction to tell how many years remain.
- Use
input()
to get age andint()
to convert it - Check if the age is
>= 18
- If not, subtract the age from 18 to calculate the wait time
- Print a different message for each case
Common Mistakes
One common mistake is forgetting to convert the input to an integer, which causes comparison to fail since strings can’t be reliably compared numerically. Another mistake is
using a single equal sign =
instead of ==
, or forgetting the correct syntax for branching statements. Some beginners also print a generic message
instead of showing how long the user has to wait.
- Not converting input: Always use
int()
aroundinput()
for numeric comparison. Otherwise, you're comparing strings. - Incorrect use of assignment: Writing
if age = 18
will result in a syntax error. Use==
only for equality checks. - No message differentiation: Some users print the same message regardless of age, which defeats the purpose of branching logic.
- Negative results: Be careful with your math — if age is already over 18, don't subtract unnecessarily.
- Misleading condition order: If your checks are written in the wrong order, logic flow might break or print the wrong result.
Step-by-Step Thinking
Imagine you're building a self-check tool at a DMV kiosk. You need to evaluate whether someone meets the age requirement for driving. Here’s how to structure it:
- Ask the user to enter their age using
input()
- Convert the age to an integer using
int()
- Compare the age with 18 using a conditional
- If age ≥ 18, print an eligibility message
- If age < 18, subtract from 18 to find years left
- Print a helpful message showing how many years remain
How to Make it Harder
Add more complexity by evaluating additional legal activities like voting or renting a car. This creates more branches and deeper logic trees.
- Check multiple age-based milestones like voting (18), renting a car (25), or senior discounts (65)
- Use
elif
blocks for multi-range messages - Let the user enter a second age (e.g., their friend’s) and compare both
- Add a loop that keeps asking for valid input until a positive number is entered
Intermediate-Level Practice – Comparison Operators in Python
At the intermediate level, comparison operators are used within multi-condition logic, branching workflows, and real-world validations. These tasks challenge you to combine
multiple comparisons, work with different data types, and apply your logic inside conditional structures such as if-elif-else
or user-driven forms. You'll simulate
login systems, form validations, and more realistic decision trees where different branches depend on more than one factor.
1. Secure Login Validation
Create a program that simulates a basic login system. The correct username is "admin"
and the correct password is "1234"
. Ask the user to input both
values, then compare them to the correct credentials. If both match, print “Access granted.” Otherwise, print “Access denied.” If only one of the inputs is incorrect, print a
specific message for that.
What this Task Teaches
This task focuses on evaluating multiple comparison expressions using logical operators (and
, or
). It also builds your understanding of how
authentication systems work and how to handle different failure cases cleanly through conditional branching and string comparisons.
- Comparing string input using
==
- Using
and
andor
for combined conditions - Creating branching logic with
if
,elif
, andelse
- Handling partial correctness (e.g., correct username, wrong password)
Hints and Tips
Focus on comparing both fields separately before combining them. Check for full success and partial mismatch conditions with clear logic flow.
- Get the username and password using
input()
- Compare them separately before combining conditions
- Use
if
for both correct,elif
for partial match,else
for full failure - Pay attention to letter casing in comparisons
Common Mistakes
Mistakes often involve comparing strings incorrectly, skipping the partial match logic, or placing and
logic inside the wrong branch. Another issue is poor message
clarity when login fails.
-
Skipping
elif
: Not handling the case where only one input is wrong leads to a missed user experience opportunity. - Incorrect logical operators: Using
or
whenand
is needed grants access too easily. - Not handling case sensitivity:
"Admin"
is not equal to"admin"
. - Hardcoding wrong values: Forgetting to use variables to compare user input leads to unnecessary rigidity.
- Poor feedback: Not telling the user which part of the login failed causes confusion and frustration.
Step-by-Step Thinking
Think like a login form: two inputs are compared against stored values. The outcome depends on matching both. If only one is wrong, explain what’s incorrect. Clear logic = secure systems.
- Ask the user for a username and password using
input()
- Compare each one to the expected values
- If both are correct, print “Access granted”
- If only one is wrong, specify which one (use
elif
) - Otherwise, print a general denial message
How to Make it Harder
Add more complexity such as password retry attempts, case-insensitive checks, or limited tries. This simulates more realistic login mechanisms.
- Allow only 3 login attempts using a loop
- Make login case-insensitive by using
.lower()
or.casefold()
- Log incorrect login attempts for auditing
- Check against multiple possible usernames and passwords (like a small user database)
2. Product Discount Checker
Create a program that helps a user check if a product is eligible for a discount. The user should input the product's original price and the amount of the discount they want to apply. The program should check that the discount is not greater than 50% of the original price and that the discounted price is still at least $1. If both conditions are satisfied, show the new discounted price. Otherwise, print a message explaining why the discount is invalid.
What this Task Teaches
This task strengthens your ability to compare two related numeric values and combine multiple conditions using and
. It helps reinforce reasoning around thresholds,
limits, and minimum allowed values, which are common in business logic, pricing engines, and ecommerce systems. You’ll also apply conditional output depending on the evaluation
result.
- Comparing percentages and numeric thresholds
- Using
and
to enforce multiple rules simultaneously - Preventing invalid input or unrealistic scenarios (like negative pricing)
- Giving helpful feedback based on failed conditions
Hints and Tips
Start by converting the discount value into a percentage of the original price, and then check if it exceeds 50%. Then calculate the new price and compare it to the $1 minimum. Be sure to handle decimal values accurately.
- Convert user input to
float
for prices - Use
discount <= original_price * 0.5
to validate percentage - Ensure final price is
>= 1
before approving - Use
if
andelse
orif-elif-else
for output
Common Mistakes
Developers sometimes forget to validate both conditions, or they perform incorrect calculations. Misplacing parentheses or failing to convert input types also leads to incorrect logic.
- Using wrong comparison order: Comparing
0.5 * discount >= original_price
instead of the other way around will break the logic. - Not converting inputs: Without converting to float, decimal-based logic fails and may raise errors when multiplying strings.
- Overlooking both conditions: Only checking one rule (like percent only, not price floor) leads to flawed business logic.
- Hardcoding values incorrectly: Using fixed price comparisons like
discount > 100
misses proportional logic. - Poor error feedback: Not telling the user why the discount is invalid makes debugging and usage harder.
Step-by-Step Thinking
Approach this task like validating a shopping cart rule: you're enforcing business constraints and informing users why their action is valid or not. Validate percentage, then check result.
- Ask the user to enter the product's original price and discount amount
- Convert both values to float to handle cents
- Check if the discount is less than or equal to 50% of the original price
- Subtract the discount and calculate the final price
- Check if the final price is at least $1
- If both checks pass, print the discounted price
- If either fails, explain why the discount is not allowed
How to Make it Harder
Add more realism by applying tax or multiple discount rules. This will push your logic deeper and prepare you for multi-condition evaluation in real software.
- Apply a tax rate after the discount and ensure total remains valid
- Allow different discount rules based on product type (e.g., electronics, clothing)
- Allow promotional codes that override the 50% rule if valid
- Round all output prices to two decimal places for clarity
Advanced-Level Practice – Comparison Operators in Python
At the advanced level, comparison operators are combined with more complex structures like nested conditions, data validation systems, and multi-step user flows. These tasks challenge you to reason through multiple outcomes, incorporate real-world rules, and maintain clear logic even when dealing with edge cases. You’ll go beyond simple true/false checks to build systems that reflect how real-world programs make decisions based on multiple inputs and outcomes.
1. College Admission Evaluator
Create a program that checks whether a student qualifies for admission based on three criteria: their GPA, entrance exam score, and whether they have any disciplinary issues.
The requirements are: GPA must be at least 3.0, exam score must be 85 or higher, and the student must have no disciplinary issues (input as "yes"
or
"no"
). Print different messages depending on which condition fails. If all are met, print “Admission approved.”
What this Task Teaches
This task trains you to evaluate multiple independent conditions using comparison and logical operators. You'll practice combining boolean expressions to model real-world decision making, where access or approval depends on satisfying several rules. It also builds fluency with user input validation and clear feedback systems.
- Evaluating multiple comparison-based conditions
- Using
and
to ensure all requirements are met - Branching logic for different failure scenarios
- Combining numeric and string comparisons logically
Hints and Tips
Focus on collecting and validating each input separately. Then evaluate each rule, combine them using and
, and handle different outcomes with
if-elif-else
.
- Convert GPA and exam score to float/int for comparisons
- Use
disciplinary == "no"
to check behavior - Use
and
to combine all three checks - Use
elif
to explain which requirement is not met
Common Mistakes
Common issues include misusing and
/or
, mishandling input types, or skipping failure messages for individual conditions. Students may also check all
values in one block instead of giving detailed feedback.
-
Using
or
instead ofand
: This causes the program to approve candidates who only meet one condition, which isn’t secure logic. -
Wrong type handling: Failing to convert GPA or exam scores to
float
/int
leads to string comparison issues and unexpected behavior. - Hardcoded boolean values: Beginners may incorrectly check
disciplinary == True
instead of comparing to a string like"no"
. - Skipping failure reasons: Users won’t understand why their application failed if you don’t branch your logic clearly.
- Nested confusion: Writing deeply nested
if
blocks without clarity reduces readability and maintainability.
Step-by-Step Thinking
Break this down as a rule engine: you’re evaluating multiple conditions separately, then combining their results. Each condition should be clear and actionable.
- Ask for GPA, exam score, and whether the student has disciplinary issues
- Convert GPA and exam score to appropriate numeric types
- Compare GPA ≥ 3.0, exam ≥ 85, and disciplinary == “no”
- Use
if
block to check all conditions at once - If all pass, approve the admission
- Else, explain which condition(s) failed
How to Make it Harder
Add conditions for specific majors, scholarships, or alternate acceptance if two out of three conditions are met. This adds nested or fallback logic.
- Add special rules for scholarships (e.g., GPA ≥ 3.8 or exam ≥ 95)
- Introduce a fallback "waitlist" if only 2 out of 3 conditions are met
- Require input for intended major and allow exceptions for specific departments
- Print detailed evaluation reports summarizing the decision
2. Vacation Eligibility Checker
Write a program for an HR system that checks if an employee is eligible for vacation approval. The rules are: the employee must have worked at least 12 months, taken fewer than 20 vacation days this year, and received a performance rating of 4.0 or higher. Ask the user to input months worked, number of vacation days used, and performance rating. Determine if the employee qualifies or not, and print specific messages if they don’t meet certain conditions.
What this Task Teaches
This task teaches you how to implement real-life HR logic using layered comparisons and conditionals. You’ll work with thresholds, numeric logic, and message feedback while handling multiple input types. This mirrors logic in leave-management systems, approval gates, and decision matrices.
- Multiple comparisons and thresholds in a business scenario
- Using
if-elif-else
for detailed user feedback - Combining
and
with numeric conditions - Handling different input data types and validation steps
Hints and Tips
Validate all three inputs carefully. Handle each rule individually before combining them. The best practice is to first check for disqualifiers and give specific feedback.
- Use
int()
for months and vacation days,float()
for ratings - Compare months ≥ 12, days used < 20, rating ≥ 4.0
- Use separate
if
orelif
blocks to explain failures - Keep messages clear and relevant to each rule
Common Mistakes
Errors often involve mismatching data types, using the wrong comparison logic, or skipping detailed user feedback. Beginners may also mistakenly use nested
if
instead of combining checks.
- Incorrect logical grouping: Using
or
instead ofand
may allow people to qualify when they shouldn’t. - Not using numeric types: Vacation days or rating as a string will cause logic errors or unexpected behavior.
- Giving unclear rejection reasons: Not explaining which rule the user failed makes the app less useful.
- Forgetting decimal comparisons: Comparing ratings like
rating > 4
instead of>= 4.0
results in skipped valid users. - Hardcoded fallback message: Avoid printing just “Denied” — tell the user why.
Step-by-Step Thinking
This is like building a rules engine for vacation logic. You're simulating real-life evaluation across several dimensions. Keep checks modular and combine them for the final decision.
- Ask the user for months worked, vacation days used, and performance rating
- Convert values appropriately: int or float
- Check if months ≥ 12, days used < 20, and rating ≥ 4.0
- If all pass, approve the vacation request
- Else, print reasons for disqualification
How to Make it Harder
Make this system smarter by adding rules for different employee levels or customizing vacation thresholds. This helps you work with dynamic branching and user input filtering.
- Ask for employee level and adjust rules (e.g., managers need rating ≥ 4.5)
- Allow partial eligibility: e.g., offer half-vacation if one rule fails
- Include a retry mechanism or option to appeal denial
- Log decisions with timestamps or summaries