0
0
PythonHow-ToBeginner · 3 min read

How to Use Comparison Operators in Python: Syntax and Examples

In Python, comparison operators compare two values and return True or False. Common operators include == (equal), != (not equal), < (less than), > (greater than), <= (less or equal), and >= (greater or equal). Use them in expressions to check conditions.
📐

Syntax

Comparison operators compare two values and return a Boolean result: True or False.

  • ==: Checks if two values are equal.
  • !=: Checks if two values are not equal.
  • <: Checks if left value is less than right value.
  • >: Checks if left value is greater than right value.
  • <=: Checks if left value is less than or equal to right value.
  • >=: Checks if left value is greater than or equal to right value.
python
a = 5
b = 10

print(a == b)   # False
print(a != b)   # True
print(a < b)    # True
print(a > b)    # False
print(a <= 5)   # True
print(b >= 10)  # True
Output
False True True False True True
💻

Example

This example shows how to use comparison operators to compare numbers and print the results.

python
x = 7
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

print("Is x equal to 7?", x == 7)
print("Is x not equal to 10?", x != 10)
Output
x is greater than 5 Is x equal to 7? True Is x not equal to 10? True
⚠️

Common Pitfalls

One common mistake is using a single = (assignment) instead of == (comparison), which causes errors or unexpected behavior.

Also, mixing types without care can lead to unexpected results, like comparing a number and a string.

python
value = 10

# Wrong: assignment instead of comparison
# if value = 10:
#     print("Value is 10")  # This causes a syntax error

# Correct:
if value == 10:
    print("Value is 10")

# Comparing different types
print(5 == '5')  # False because int and str are different
Output
Value is 10 False
📊

Quick Reference

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than7 > 10False
<=Less than or equal to5 <= 5True
>=Greater than or equal to10 >= 7True

Key Takeaways

Use comparison operators to check relationships between values and get True or False.
Remember to use '==' for comparison, not '=' which is for assignment.
Comparison operators work with numbers, strings, and other comparable types.
Be careful comparing different data types to avoid unexpected results.
Common operators include ==, !=, <, >, <=, and >=.