Logical Operators
Introduction to Logical Operators
Logical operators are fundamental tools in Python for combining and manipulating Boolean values. They allow you to create complex conditions and control program flow.
Three Main Logical Operators
Python provides three primary logical operators:
Operator |
Symbol |
Description |
AND |
and |
Returns True if both conditions are True |
OR |
or |
Returns True if at least one condition is True |
NOT |
not |
Inverts the Boolean value |
AND Operator
The and
operator requires all conditions to be True
:
## AND operator examples
x = 5
y = 10
z = 15
print(x < y and y < z) ## True
print(x > y and y < z) ## False
OR Operator
The or
operator returns True
if at least one condition is True
:
## OR operator examples
is_weekend = False
is_holiday = True
print(is_weekend or is_holiday) ## True
print(False or False) ## False
NOT Operator
The not
operator inverts the Boolean value:
## NOT operator examples
is_raining = False
print(not is_raining) ## True
is_sunny = True
print(not is_sunny) ## False
Complex Logical Expressions
You can combine multiple logical operators:
## Complex logical expressions
age = 25
has_license = True
is_insured = False
can_drive = age >= 18 and has_license and not is_insured
print(can_drive) ## True
Short-Circuit Evaluation
Python uses short-circuit evaluation for logical operators:
## Short-circuit evaluation
def is_valid_user(username):
return username and len(username) > 3
print(is_valid_user('')) ## False
print(is_valid_user('LabEx')) ## True
Operator Precedence
graph TD
A[Logical Operators Precedence] --> B[NOT highest priority]
A --> C[AND medium priority]
A --> D[OR lowest priority]
Best Practices
- Use parentheses to clarify complex conditions
- Avoid overly complicated logical expressions
- Break down complex conditions into smaller, readable parts
Practical Example
## Real-world logical operator usage
def can_register_for_course(age, has_prerequisites, is_enrolled):
return (age >= 18) and has_prerequisites and not is_enrolled
## LabEx course registration logic
print(can_register_for_course(20, True, False)) ## True
print(can_register_for_course(17, True, False)) ## False
By mastering these logical operators, you'll be able to create more sophisticated and precise conditional logic in your Python programs.