In programming, we often need to compare values or decide based on multiple conditions. Python provides comparison operators to compare values and logical operators to combine conditions for complex decision-making.
Comparison operators
Comparison operators evaluate two values and return a boolean result: True
False
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 8 > 5 |
True |
< |
Less than | 3 < 6 |
True |
>= |
Greater than or equal to | 7 >= 7 |
True |
<= |
Less than or equal to | 4 <= 4 |
True |
Practical examples
Equality ==
password = "secure123"
print(input_password == password) # True if passwords match
Inequality !=
data = 42
print(data != 0) # True if data is not zero
Greater or Less Than (>
or <
): Compare scores or thresholds.
score = 85
print(score > 70) # True if the score exceeds 70
Logical operators
Logical operators combine multiple conditions into one, enabling more complex logic.
Operator | Description | Example | Result |
---|---|---|---|
and |
True if both conditions are true | (5 > 3) and (10 > 7) |
True |
or |
True if at least one condition is true | (5 > 3) or (10 < 7) |
True |
not |
Reverses the result of a condition | not (5 > 3) |
False |
Practical examples
: Check if a number is within a range.
age = 25
print((age > 18) and (age < 65)) # True if age is between 18 and 65
: Identify acceptable options.
day = "Saturday"
print((day == "Saturday") or (day == "Sunday")) # True for weekends
: Validate a negative condition.
logged_in = False
print(not logged_in) # True if not logged in
Combining operators
You can mix comparison and logical operators to handle complex logic.
Example: Admission check
age = 20
has_ID = True
can_enter = (age >= 18) and has_ID
print(can_enter) # True if age is at least 18 and ID is present
Real-World applications
- Verify access to restricted content.
- Validate multi-factor authentication criteria.
Operator precedence
When combining operators, Python evaluates them in a specific order, similar to PEMDAS in arithmetic:
- Parentheses
()
- Comparison operators
,==
!= ,> ,< ,>= ,<= - Logical NOT
not
- Logical AND
and
- Logical OR
or
Example
x = 5
y = 10
z = 15
result = (x < y) and (y < z) or not (x == 5)
print(result) # Output: True
Conclusion
Comparison and logical operators are vital tools for building decision-making logic in Python. They allow you to evaluate conditions, combine multiple criteria, and implement real-world scenarios like access control or data validation effectively.