Python tutorials | Understanding Comparison Operators in Python

Comparison operators are used to compare two values. They evaluate expressions and return a Boolean result: either True or False. These operators are especially useful in conditions and loops.

Python provides six main comparison operators: ==, !=, >, <, >=, and <=.

Example 1: Equal To (==)

a = 10
b = 10
print(a == b)

Returns True because both values are equal.

Example 2: Not Equal To (!=)

name1 = "Alice"
name2 = "Bob"
print(name1 != name2)

Returns True since the strings are different.

Example 3: Greater Than (>)

marks = 85
print(marks > 75)

Returns True if the first value is greater than the second.

Example 4: Less Than (<)

x = 5
y = 10
print(x < y)

Returns True because 5 is less than 10.

Example 5: Greater Than or Equal To (>=)

score = 90
print(score >= 90)

This returns True because the value is equal to 90.

Example 6: Less Than or Equal To (<=)

age = 17
print(age <= 18)

Returns True since 17 is less than 18.

Example 7: Comparison in if Statement

temperature = 38
if temperature > 37:
    print("Fever detected")

Comparison operators are often used in if statements to control flow.

Example 8: Comparing Strings

word1 = "apple"
word2 = "banana"
print(word1 < word2)

Strings are compared based on their Unicode order. Returns True.

Example 9: Comparing Lists

list1 = [1, 2, 3]
list2 = [1, 2, 4]
print(list1 < list2)

Lists are compared element by element. Returns True because 3 is less than 4.

Example 10: Boolean Result of Comparison

result = 100 == (50 * 2)
print(result)

Comparison expressions return Boolean values which can be stored in variables or used in logic.


Summary

  • == checks if values are equal
  • != checks if values are not equal
  • > checks if the first value is greater
  • < checks if the first value is smaller
  • >= checks if the first value is greater or equal
  • <= checks if the first value is smaller or equal

Understanding comparison operators is essential for writing effective conditions, filtering data, and building logic in Python programs.