Comparison Operators
Comparison operators in Python are used to compare two values, expressions, or variables. They allow you to determine whether a given condition is true or false. Python provides a variety of comparison operators for this purpose.
1. Equality Operator (==)
The equality operator (==
) checks if two values are equal. It returns True
if they are equal and False
otherwise. For example:
x = 5
y = 5
result = x == y # True
2. Inequality Operator (!=)
The inequality operator (!=
) checks if two values are not equal. It returns True
if they are not equal and False
if they are. For example:
x = 5
y = 10
result = x != y # True
3. Greater Than Operator (>)
The greater than operator (>
) checks if the value on the left is greater than the value on the right. It returns True
if the condition is met and False
otherwise. For example:
x = 10
y = 5
result = x > y # True
4. Less Than Operator (<)
The less than operator (<
) checks if the value on the left is less than the value on the right. It returns True
if the condition is met and False
otherwise. For example:
x = 5
y = 10
result = x < y # True
5. Greater Than or Equal To Operator (>=)
The greater than or equal to operator (>=
) checks if the value on the left is greater than or equal to the value on the right. It returns True
if the condition is met and False
otherwise. For example:
x = 10
y = 10
result = x >= y # True
6. Less Than or Equal To Operator (<=)
The less than or equal to operator (<=
) checks if the value on the left is less than or equal to the value on the right. It returns True
if the condition is met and False
otherwise. For example:
x = 5
y = 10
result = x <= y # True
Comparison operators are frequently used in conditional statements and expressions to make decisions based on the evaluation of conditions. They allow you to create dynamic and responsive code by comparing values and determining their relationships.