⚖️ Comparing Values

Comparing values is one of the most fundamental operations in programming. Python's comparison operators let you determine relationships between different pieces of data—whether numbers are equal, which value is larger, or if a condition is met. These comparisons form the foundation of decision-making in your programs.

Comparison operators always return either True or False, making them perfect for creating conditions that control how your program behaves. Whether you're checking if a user entered the correct password, determining if a student passed a test, or finding the highest score in a game, comparison operators make these decisions possible.

# Basic comparison operations
print("=== BASIC COMPARISONS ===")

a = 10
b = 5
c = 10

print(f"{a} == {c}: {a == c}")    # True (equal to)
print(f"{a} > {b}: {a > b}")      # True (greater than)
print(f"{b} < {a}: {b < a}")      # True (less than)
print(f"{a} != {b}: {a != b}")    # True (not equal to)

🎯 Equality Operators

Equality operators check whether two values are the same or different. These are among the most commonly used comparison operators in programming.

# Equality comparisons
print("=== EQUALITY TESTS ===")

# Numbers
score1 = 85
score2 = 85
score3 = 92

print(f"score1 == score2: {score1 == score2}")      # True
print(f"score1 != score3: {score1 != score3}")      # True

# Text (case-sensitive!)
name1 = "Alice"
name2 = "alice"  
name3 = "Alice"

print(f"'{name1}' == '{name3}': {name1 == name3}")  # True
print(f"'{name1}' == '{name2}': {name1 == name2}")  # False (case matters!)

# Mixed types (int/float comparison)
int_num = 10
float_num = 10.0
print(f"{int_num} == {float_num}: {int_num == float_num}")  # True

📏 Relational Operators

Relational operators compare the relative size or order of values. They help you determine which value is larger, smaller, or if values fall within certain ranges.

# Relational comparisons
print("=== RELATIONAL TESTS ===")

age = 18
min_age = 16
max_age = 65

print(f"age >= min_age: {age >= min_age}")      # True
print(f"age <= max_age: {age <= max_age}")      # True

# Temperature check
temperature = 75
print(f"Temperature {temperature}°F:")
print(f"  Above freezing (>32): {temperature > 32}")        # True
print(f"  Below boiling (<=212): {temperature <= 212}")     # True

# String comparisons (alphabetical order)
word1 = "apple"
word2 = "banana"
print(f"'{word1}' < '{word2}': {word1 < word2}")           # True (alphabetical)

🔗 Chaining Comparisons

Python allows you to chain multiple comparisons together, creating more natural and readable conditions. This feature makes it easy to check if a value falls within a range or meets multiple criteria.

# Chained comparisons
print("=== CHAINED COMPARISONS ===")

score = 85
temperature = 72
age = 25

# Check if score is in a range
passing_range = 60 <= score <= 100
print(f"Score {score} is passing (60-100): {passing_range}")        # True

# Check if temperature is comfortable
comfortable = 65 <= temperature <= 80
print(f"Temperature {temperature}°F is comfortable: {comfortable}")  # True

# Check working age range
valid_age = 18 <= age <= 65
print(f"Age {age} is in working range (18-65): {valid_age}")        # True

🔄 Comparing Different Data Types

Python's comparison operators work with various data types, each with their own comparison rules. Understanding how different types compare helps you write more effective conditional logic.

# Different data type comparisons
print("=== DATA TYPE COMPARISONS ===")

# Mixed number types
int_num = 10
float_num = 10.0
print(f"{int_num} == {float_num}: {int_num == float_num}")    # True

# String comparisons (case matters!)
word1 = "Apple"
word2 = "banana"
print(f"'{word1}' < '{word2}': {word1 < word2}")            # True ('A' < 'b')

# Boolean comparisons
result1 = True
result2 = False
print(f"True > False: {result1 > result2}")                  # True
print(f"True == 1: {result1 == 1}")                          # True
print(f"False == 0: {result2 == 0}")                         # True

# Float precision issue demonstration
result = 0.1 + 0.2
expected = 0.3
print(f"0.1 + 0.2 == 0.3: {result == expected}")            # False! (precision issue)
print(f"Close enough: {abs(result - expected) < 1e-9}")     # True (tolerance method)

💼 Practical Applications

Comparison operators are essential for creating intelligent programs that respond to different conditions. They're used in decision-making, validation, filtering data, and controlling program flow.

# Practical comparison examples
print("=== PRACTICAL EXAMPLES ===")

# Password validation
password = "MySecret123"
min_length = 8
has_min_length = len(password) >= min_length
print(f"Password meets minimum length: {has_min_length}")

# Grade evaluation (using chained comparisons)
test_score = 85
if 90 <= test_score <= 100:
    grade = "A"
elif 80 <= test_score < 90:
    grade = "B"
elif 70 <= test_score < 80:
    grade = "C"
else:
    grade = "F"
print(f"Score {test_score} gets grade: {grade}")

# Shopping budget check
item_price = 25.99
budget = 30.00
can_afford = item_price <= budget
print(f"Can afford ${item_price} with ${budget} budget: {can_afford}")

# Even number check using modulus
number = 42
is_even = number % 2 == 0
print(f"{number} is even: {is_even}")

📊 Working with Comparison Results

Comparison operations return boolean values (True or False) that can be stored in variables, used in conditions, or combined with logical operators. Understanding how to work with these boolean results is key to building complex program logic.

# Working with comparison results
print("=== COMPARISON RESULTS ===")

# Store results in variables
user_age = 22
is_adult = user_age >= 18
is_senior = user_age >= 65
is_working_age = 18 <= user_age <= 65

print(f"Age {user_age}:")
print(f"  Is adult: {is_adult}")
print(f"  Is senior: {is_senior}")
print(f"  Is working age: {is_working_age}")

# Using results in decisions
account_balance = 150.00
minimum_balance = 100.00

if account_balance >= minimum_balance:
    print("Account balance is sufficient")
else:
    print("Account balance is too low")

🔍 Quick Comparison Practice

Let's practice using comparison operators to check different conditions!

Hands-on Exercise

Practice using comparison operators like ==, !=, <, >, <=, >= to compare values.

python
# Comparison Practice - Simple checks!

# Test scores
math_score = 85
english_score = 92
passing_grade = 70

# Check if scores are passing
math_passing = # TODO: Your code here (math_score >= passing_grade)
english_passing = # TODO: Your code here (english_score >= passing_grade)

# Check which score is higher
math_higher = # TODO: Your code here (math_score > english_score)

# Check if both scores are equal
scores_equal = # TODO: Your code here (math_score == english_score)

print(f"Math score {math_score} is passing: {math_passing}")
print(f"English score {english_score} is passing: {english_passing}")
print(f"Math score is higher: {math_higher}")
print(f"Scores are equal: {scores_equal}")

Solution and Explanation 💡

Click to see the complete solution
# Comparison Practice - Simple solution

# Test scores
math_score = 85
english_score = 92
passing_grade = 70

# Check if scores are passing
math_passing = math_score >= passing_grade     # Greater than or equal
english_passing = english_score >= passing_grade   # Greater than or equal

# Check which score is higher
math_higher = math_score > english_score      # Greater than

# Check if both scores are equal
scores_equal = math_score == english_score    # Equal to

print(f"Math score {math_score} is passing: {math_passing}")
print(f"English score {english_score} is passing: {english_passing}")
print(f"Math score is higher: {math_higher}")
print(f"Scores are equal: {scores_equal}")

Key Learning Points:

  • 📌 >= operator: Checks if greater than or equal (passing grade)
  • 📌 > operator: Checks if strictly greater than (higher score)
  • 📌 == operator: Checks if values are equal
  • 📌 Boolean results: All comparisons return True or False

📚 Comparison Operators Reference

OperatorNameExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than3 < 5True
>=Greater than or equal5 >= 5True
<=Less than or equal3 <= 5True

Understanding comparison operators prepares you for logical operations and decision making with if statements. These operators are also essential for working with loops and data filtering.

Test Your Knowledge

🚀 What's Next?

Now that you understand how to compare values, you're ready to learn about combining multiple comparisons using logical operators. Comparison operators often work together with logical operators to create sophisticated decision-making logic.

In the next lesson, we'll explore Logic Operations, where you'll learn how to combine multiple conditions using and, or, and not operators.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent