Python

In Python, Comparison Operators (also known as Relational Operators) are used to compare two values or operands. The result of a comparison is always a Boolean value: either True or False.

These operators are the backbone of decision-making in programming, allowing you to control the flow of your logic based on specific conditions.

1. Theoretical Overview

Comparison operators evaluate the relationship between two entities. In Python, you can compare numbers, strings, and even more complex data structures like lists or sets.

List of Comparison Operators

OperatorNameDescriptionExample (a=10,b=20)
==Equal toReturns True if operands are equal.(a == b) is False
!=Not equal toReturns True if operands are NOT equal.(a != b) is True
>Greater thanTrue if left is greater than right.(a > b) is False
<Less thanTrue if left is less than right.(a < b) is True
>=Greater than or equal toTrue if left is greater than or equal to right.(a >= b) is False
<=Less than or equal toTrue if left is less than or equal to right.(a <= b) is True

2. Key Behaviors & Nuances

A. Equality (==) vs. Assignment (=)

A common beginner mistake is using a single equals sign for comparison.

  • x = 5 assigns the value 5 to x.

  • x == 5 checks if x is equal to 5.

B. String Comparison

Python compares strings based on ASCII/Unicode values (lexicographical order).

  • Lowercase letters have higher values than uppercase letters (e.g., 'a' > 'A' is True).

  • Example: "apple" < "banana" is True because 'a' comes before 'b'.

C. Chaining Operators

Python allows you to chain multiple comparisons in a single expression, which is more readable than using logical operators.

  • Example: 5 < x < 10 is valid and checks if $x$ is between 5 and 10.

3. Code Implementation

Python
# Numerical Comparisons
x = 10
y = 15

print(f"Is {x} equal to {y}? {x == y}")        # False
print(f"Is {x} not equal to {y}? {x != y}")    # True
print(f"Is {x} greater than {y}? {x > y}")     # False
print(f"Is {y} >= 15? {y >= 15}")              # True

# String Comparisons
str1 = "Hello"
str2 = "hello"
print(f"Is '{str1}' == '{str2}'? {str1 == str2}") # False (Case-sensitive)

# Chaining Example
age = 25
is_eligible = 18 <= age <= 60
print(f"Is age {age} within range (18-60)? {is_eligible}") # True

# Comparison with expressions
print(f"Is 5 + 5 == 10? {5 + 5 == 10}")        # True

4. Practical Use Case: Conditional Logic

Comparison operators are almost always used with if statements to execute specific blocks of code.

Python
temperature = 30

if temperature > 25:
    print("It's a hot day!")
else:
    print("The weather is pleasant.")
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now