Now that you know how to store data using variables, the next logical step is to learn how to compare them. Comparison operators are fundamental for making decisions in your programs. They allow you to check if two values are equal, if one is greater than the other, and so on. The result of a comparison is always a boolean value: True or False.
Let's explore the different comparison operators available in Python:
- Equal to (
==): This operator checks if two values are equal. It's important to distinguish this from the assignment operator (=), which assigns a value to a variable.==compares values.
x = 10
y = 10
z = 5
print(x == y) # Output: True
print(x == z) # Output: False- Not equal to (
!=): This operator checks if two values are not equal. If they are different, it returnsTrue; otherwise, it returnsFalse.
a = 'hello'
b = 'world'
c = 'hello'
print(a != b) # Output: True
print(a != c) # Output: False- Greater than (
>): This operator checks if the value on the left is strictly greater than the value on the right.
score1 = 95
score2 = 88
print(score1 > score2) # Output: True
print(score2 > score1) # Output: False- Less than (
<): This operator checks if the value on the left is strictly less than the value on the right.
temperature = 25
freezing_point = 0
print(temperature < freezing_point) # Output: False
print(freezing_point < temperature) # Output: True- Greater than or equal to (
>=): This operator checks if the value on the left is greater than or equal to the value on the right. It returnsTrueif either condition is met.