PythonComparison Operators

Comparison Operators in Python

Comparison operators (also called relational operators) are used to compare two values. The result is always a boolean value: True or False.

These operators are essential for decision-making, such as in if statements and loops.


List of Comparison Operators

OperatorSymbolDescription
Equal==Returns True if both operands are equal
Not Equal!=Returns True if operands are not equal
Greater Than>Returns True if left operand is greater
Less Than<Returns True if left operand is lesser
Greater Than or Equal>=True if left operand is greater or equal
Less Than or Equal<=True if left operand is less or equal

1. Equal To (==)

Checks if two values are equal.

equal.py
a = 10
b = 10
print(a == b)
output.txt
True

Example 2: Comparing Strings

equal_strings.py
name1 = "Alice"
name2 = "alice"
print(name1 == name2)
output.txt
False

Example 3: Comparing Different Types

equal_types.py
num = 10
text = "10"
print(num == text)
output.txt
False

2. Not Equal (!=)

Checks if two values are not equal.

not_equal.py
x = 7
y = 5
print(x != y)
output.txt
True

Example 2: Strings Comparison

not_equal_strings.py
first = "Python"
second = "Java"
print(first != second)
output.txt
True

Example 3: Comparing Different Types

not_equal_types.py
a = 5
b = "5"
print(a != b)
output.txt
True

3. Greater Than (>)

Checks if the left operand is greater than the right.

greater_than.py
a = 15
b = 10
print(a > b)
output.txt
True

Example 2: Floats Comparison

greater_than_floats.py
x = 7.8
y = 9.2
print(x > y)
output.txt
False

Example 3: Negative Numbers

greater_than_negative.py
a = -2
b = -5
print(a > b)
output.txt
True

4. Less Than (<)

Checks if the left operand is less than the right.

less_than.py
x = 8
y = 12
print(x < y)
output.txt
True

Example 2: Floats Comparison

less_than_floats.py
x = 2.5
y = 1.5
print(x < y)
output.txt
False

Example 3: Negative Numbers

less_than_negative.py
a = -10
b = -1
print(a < b)
output.txt
True

5. Greater Than or Equal (>=)

Checks if the left operand is greater than or equal to the right.

greater_equal.py
a = 10
b = 10
print(a >= b)
output.txt
True

Example 2: Floats

greater_equal_floats.py
x = 5.0
y = 4.9
print(x >= y)
output.txt
True

Example 3: Negative Comparison

greater_equal_negative.py
a = -2
b = -3
print(a >= b)
output.txt
True

6. Less Than or Equal (<=)

Checks if the left operand is less than or equal to the right.

less_equal.py
a = 8
b = 12
print(a <= b)
output.txt
True

Example 2: Floats

less_equal_floats.py
x = 4.4
y = 4.4
print(x <= y)
output.txt
True

Example 3: Negative Values

less_equal_negative.py
a = -5
b = -1
print(a <= b)
output.txt
True

Summary

  • Comparison operators evaluate relationships between two values.
  • They return a boolean result (True or False).
  • Used commonly in conditional statements (if, while) and loops.
  • Work with numbers, floats, strings, and other comparable types.
Last updated on