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.
age = 18
minimum_age = 18
print(age >= minimum_age) # Output: True
print(17 >= minimum_age) # Output: False- Less than or equal to (
<=): This operator checks if the value on the left is less than or equal to the value on the right. It returnsTrueif either condition is met.
inventory = 50
reorder_level = 50
print(inventory <= reorder_level) # Output: True
print(51 <= reorder_level) # Output: Falsegraph TD
A[Start]
B{Compare Values}
C[Equal ==]
D[Not Equal !=]
E[Greater Than >]
F[Less Than <]
G[Greater Than or Equal >=]
H[Less Than or Equal <=]
I[Returns True or False]
J[End]
A --> B
B --> C
B --> D
B --> E
B --> F
B --> G
B --> H
C --> I
D --> I
E --> I
F --> I
G --> I
H --> I
I --> J
These comparison operators are the building blocks for creating programs that can respond to different conditions. You'll see them used extensively in if statements and loops to control the flow of your program.