Comparison Operators in Python

 

What are Comparison Operators? 

Comparison operators are like judges in a coding courtroom—they compare two values and decide if they are equal, different, bigger, or smaller! 

They always return True or False (just like an honest judge).

List of Comparison Operators

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Let's see these in action! 

Equal to (==

Checks if two values are the same.

x = 5
y = 5
print(x == y)  # Output: True

z = 10
print(x == z)  # Output: False

Be careful! = is for assignment, while == is for comparison.

x = 10  # Assigns 10 to x
print(x == 10)  # Checks if x is equal to 10 (True)

Not Equal to (!=

Checks if two values are different.

x = 5
y = 10
print(x != y)  # Output: True

If they are the same, it returns False:

print(x != 5)  # Output: False

Greater than (>

Checks if the left value is bigger.

print(10 > 5)  # Output: True
print(5 > 10)  # Output: False

Less than (<

Checks if the left value is smaller.

print(5 < 10)  # Output: True
print(10 < 5)  # Output: False

Greater than or Equal to (>=

Checks if the left value is bigger OR equal.

print(10 >= 10)  # Output: True
print(10 >= 5)   # Output: True
print(5 >= 10)   # Output: False

Less than or Equal to (<=

Checks if the left value is smaller OR equal.

print(5 <= 5)   # Output: True
print(5 <= 10)  # Output: True
print(10 <= 5)  # Output: False

Using Comparison in if Statements 

Comparison operators are often used in conditions.

age = 18
if age >= 18:
    print("You can vote!")
else:
    print("Sorry, you are too young.")

Fun with Comparisons 

Comparisons also work with strings!

print("apple" == "apple")  # Output: True
print("apple" > "banana")  # Output: False (A comes before B!)

Even lists can be compared:

print([1, 2, 3] == [1, 2, 3])  # Output: True
print([1, 2] < [1, 3])  # Output: True (compares element by element)

Summary 

Operator Meaning
== Checks if two values are equal
!= Checks if two values are not equal
> Checks if left is greater than right
< Checks if left is less than right
>= Checks if left is greater than or equal to right
<= Checks if left is less than or equal to right

Now go compare everything in Python like a pro! 

 

Post a Comment

0 Comments