What are comparison operators in Python?
In Python, comparison operators are used to compare two values and return a boolean result (True
or False
). These operators are fundamental to performing conditional checks and controlling the flow of the program through constructs such as if
statements and loops. Here are the main comparison operators in Python:
List of Comparison Operators
-
Equal to (
==
):- Checks if the values of two operands are equal.
a = 5 b = 5 print(a == b) # Output: True
-
Not equal to (
!=
):- Checks if the values of two operands are not equal.
a = 5 b = 3 print(a != b) # Output: True
-
Greater than (
>
):- Checks if the value of the left operand is greater than the value of the right operand.
a = 5 b = 3 print(a > b) # Output: True
-
Less than (
<
):- Checks if the value of the left operand is less than the value of the right operand.
a = 5 b = 3 print(a < b) # Output: False
-
Greater than or equal to (
>=
):- Checks if the value of the left operand is greater than or equal to the value of the right operand.
a = 5 b = 5 print(a >= b) # Output: True
-
Less than or equal to (
<=
):- Checks if the value of the left operand is less than or equal to the value of the right operand.
a = 5 b = 8 print(a <= b) # Output: True
Usage in Conditional Statements
Comparison operators are often used in conditional statements to control the flow of a program. Here are some examples:
Example 1: Using if
Statements
a = 10 b = 20 if a < b: print("a is less than b") else: print("a is not less than b")
Output:
a is less than b
Example 2: Using if-elif-else
Statements
a = 10 b = 20 if a == b: print("a is equal to b") elif a > b: print("a is greater than b") else: print("a is less than b")
Output:
a is less than b
Example 3: Using Comparison Operators in Loops
numbers = [1, 2, 3, 4, 5] for number in numbers: if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
Combining Comparison Operators
You can combine comparison operators with logical operators (and
, or
, not
) to form complex conditions:
a = 10 b = 20 c = 15 if a < b and b > c: print("Both conditions are true") if a < b or b < c: print("At least one condition is true") if not a > b: print("a is not greater than b")
Output:
Both conditions are true
At least one condition is true
a is not greater than b
Conclusion
Comparison operators in Python are essential for evaluating conditions and making decisions in your programs. They help control the flow of the program and enable more complex logic to be implemented. Understanding and effectively using these operators is fundamental to becoming proficient in Python programming.
GET YOUR FREE
Coding Questions Catalog