Python Master Course V2 — 013. Comparison Operators
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 02 · LESSON 013 / 200
Comparison Operators — Precise Decisions and Reliable Validation
Study time: 65–90 minutes · Level: Foundations to professional practice
Prerequisites: Lesson 012 — Assignment and Augmented Assignment, numeric types, strings, and basic if statements.
1. Video lesson
Video not yet available. A verified video URL/player will be added here when supplied. This lesson is fully available in text.
2. Learning outcomes
- Explain
==,!=,<,<=,>and>=. - Distinguish equality from identity and assignment.
- Use chained comparisons and handle boundary conditions.
- Compare strings, dates, and numeric values appropriately.
- Write validation logic and test edge cases including NaN and float precision.
3. Comparison operators and how Python evaluates them
Comparisons are expressions that normally return a Boolean value, True or False. Equality (==) asks whether two values compare equal; inequality (!=) asks whether they differ. Ordering operators ask whether a value comes before or after another. For built-in numbers, ordering is numeric; for strings, ordering is lexicographic by Unicode code points, not natural-language alphabetical sorting.
Assignment is not comparison: x = 10 assigns a value, whereas x == 10 evaluates equality. is tests object identity rather than value equality; don’t use it to compare user-entered strings or numbers. Use is None for the singleton None.
Chained comparisons such as 18 <= age <= 60 express a bounded range clearly and evaluate the middle operand only once. Python short-circuits a chain when a comparison fails.
4. Progressive Python examples
Setup: Python 3.10+. Save each code block separately as lesson013.py and run python lesson013.py (or python3). Expected outputs below are provided for verification.
Example 1 — Basic comparisons
a, b = 12, 20
print(a == b)
print(a != b)
print(a < b)
print(a <= 12)
print(b >= 20)
False True True True True
Example 2 — Assignment versus equality
score = 75
print(score == 75)
print(score == 100)
print(type(score == 75).__name__)
True False bool
Example 3 — Range checks and boundaries
for age in [17, 18, 59, 60, 61]:
print(age, 18 <= age <= 60)
17 False 18 True 59 True 60 True 61 False
Example 4 — String comparisons
print("Apple" == "apple")
print("apple".casefold() == "APPLE".casefold())
print("cat" < "dog")
False True True
For user-facing text matching, normalize whitespace and case intentionally; Unicode casefolding does not replace full locale-aware collation.
Example 5 — Floating-point precision
import math
x = 0.1 + 0.2
print(x == 0.3)
print(math.isclose(x, 0.3, rel_tol=1e-9, abs_tol=0.0))
False True
Use tolerances appropriate to the problem domain. For exact decimal money values, prefer Decimal created from strings.
Example 6 — NaN is unusual
from math import nan, isnan
print(nan == nan)
print(nan < 10)
print(isnan(nan))
False False True
NaN is not equal to itself; use math.isnan() for detection.
Example 7 — Dates rather than formatted text
from datetime import date
deadline = date(2026, 12, 31)
submitted = date(2026, 12, 30)
print(submitted <= deadline)
True
Compare date objects instead of display strings like "31/12/2026".
5. Guided project — Eligibility and Invoice Validator
Scenario: A training institute admits applicants aged 18–60 inclusive, requires an exam score of at least 60, and permits invoice discounts for fees of ₹1,000 or more. Validate the values before computing eligibility. This is an illustrative classroom policy, not an official eligibility rule.
from decimal import Decimal, InvalidOperation
def assess(age_text: str, score_text: str, fee_text: str) -> str:
try:
age = int(age_text)
score = int(score_text)
fee = Decimal(fee_text)
except (ValueError, InvalidOperation):
return "Invalid input"
if not fee.is_finite() or fee < 0 or not (0 <= score <= 100) or age < 0:
return "Invalid input"
if not (18 <= age <= 60):
return "Not eligible: age"
if score < 60:
return "Not eligible: score"
discount = Decimal("0.10") if fee >= Decimal("1000") else Decimal("0")
payable = fee * (Decimal("1") - discount)
return f"Eligible | Payable INR {payable:.2f}"
print(assess("18", "60", "1000"))
print(assess("17", "95", "1000"))
print(assess("30", "59", "500"))
print(assess("60", "90", "999"))
print(assess("25", "80", "NaN"))
Expected output:
Eligible | Payable INR 900.00 Not eligible: age Not eligible: score Eligible | Payable INR 999.00 Invalid input
Project reasoning: First convert input, then reject impossible values, then apply eligibility boundaries, and only then calculate a discount. This ordering keeps business decisions readable. In production, financial rounding rules must be specified; this example uses two-decimal display formatting.
6. Common mistakes and best practices
- Writing
=instead of==inside a condition. - Using
isfor value equality. - Comparing numeric strings such as
"20" < "3"rather than converting to integers. - Ignoring inclusivity at threshold values; test below, equal to, and above every threshold.
- Comparing floats for exact equality without considering representation.
- Failing to reject non-finite Decimal values such as NaN and Infinity.
7. Exercises and model answers
-
Write a range check for a temperature between 15 and 35 inclusive.
Hint: inclusive temperature range
Use <= at both ends, and test just outside the range.
Worked answer: inclusive temperature range
Model:
15 <= temperature <= 35.for temperature in [14, 15, 35, 36]: print(temperature, 15 <= temperature <= 35)Expected output:
14 False 15 True 35 True 36 FalseThe chained comparison includes both endpoints. Testing one below and one above distinguishes an inclusive range from a strict one.
-
Check whether two user names match regardless of case and surrounding spaces.
Hint: normalized user names
Apply the same trimming and case folding to both strings.
Worked answer: normalized user names
Model:
a.strip().casefold() == b.strip().casefold().a = " Alice " b = "ALICE" print(a == b) print(a.strip().casefold() == b.strip().casefold())Expected output:
False TrueThe original strings differ in whitespace and case. Normalizing both sides makes this intended informal comparison consistent; the application must still define which spelling differences it permits.
-
Check if a number is outside 1–10.
Hint: outside the range
Negate the complete inclusive range, or join its two outside conditions with or.
Worked answer: outside the range
Model:
not (1 <= number <= 10).for number in [0, 1, 10, 11]: outside = not (1 <= number <= 10) print(number, outside, number < 1 or number > 10)Expected output:
0 True True 1 False False 10 False False 11 True TrueOne and ten are inside, so the outside check is False. Using
number < 1 and number > 10would never succeed for an ordinary number. -
Why is
0.1 + 0.2 == 0.3false?Hint: floating-point comparison
Inspect the stored result, then compare using a tolerance suitable for the calculation.
Worked answer: floating-point comparison
Model: binary floating-point approximates many decimal fractions.
import math value = 0.1 + 0.2 print(repr(value)) print(value == 0.3) print(math.isclose(value, 0.3, rel_tol=1e-9, abs_tol=1e-12))Expected output:
0.30000000000000004 False TrueExact equality compares the approximations, which differ. A tolerance expresses how close the result must be; choose it from the problem’s units and error requirements. For decimal money, use Decimal strings and an explicit rounding policy instead.
-
Extend the project to reject a score above 100 and test values 0, 60, and 101.
Hint: score validation before eligibility
The existing range guard already rejects 101; keep it before the pass threshold.
Worked answer: score validation before eligibility
Model: the existing guard
not (0 <= score <= 100)rejects 101.With a valid age of 30 and fee of ₹1,000, the project should return
Not eligible: scorefor 0,Eligible | Payable INR 900.00for 60, andInvalid inputfor 101.for score in [0, 60, 101]: if not (0 <= score <= 100): result = "Invalid input" elif score < 60: result = "Not eligible: score" else: result = "Score qualifies" print(score, result)Expected output:
0 Not eligible: score 60 Score qualifies 101 Invalid inputThis focused test isolates the score decision. In the complete project, age and fee must also pass their guards before an invoice is calculated. Checking only
score >= 60would wrongly allow 101.
8. Five-question knowledge check
- Which operator tests equality? A: =, B: ==, C: is always, D: >.
Answer: B. Assignment uses =; equality uses ==.
- What is 10 <= 10? A: False, B: True, C: Error, D: None.
Answer: B. The inclusive boundary allows equality.
- What does 18 <= age <= 60 mean? A: only 18, B: outside range, C: inclusive range, D: assignment.
Answer: C. Both comparisons must hold.
- How should two approximate floats be compared? A: always is, B: math.isclose with justified tolerances, C: convert to str, D: compare IDs.
Answer: B. Tolerances reflect acceptable numeric error.
- How do you detect a floating NaN? A: x == nan, B: x is nan, C: math.isnan(x), D: x < 0.
Answer: C. NaN comparisons do not behave like ordinary numeric equality.
9. Mastery checkpoint
You are ready for the next lesson when you can predict six comparison operators, explain equality versus identity, use inclusive range checks, test three boundary values, and extend the eligibility validator with one additional business rule.
Summary: Reliable comparisons require correct operators, appropriate data types, deliberate boundary conditions, and testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.