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.
Basic Logical Operators
Python provides three primary logical operators:
Operator |
Description |
Example |
and |
Returns True if both conditions are true |
x and y |
or |
Returns True if at least one condition is true |
x or y |
not |
Reverses the boolean value |
not x |
Logical Operator Truth Tables
graph TD
A[Logical Operators Truth Tables]
A --> B[AND Operator]
A --> C[OR Operator]
A --> D[NOT Operator]
AND Operator
## AND operator examples
print(True and True) ## True
print(True and False) ## False
print(False and True) ## False
print(False and False) ## False
## Practical example
age = 25
is_student = True
can_register = age >= 18 and is_student ## True
OR Operator
## OR operator examples
print(True or True) ## True
print(True or False) ## True
print(False or True) ## True
print(False or False) ## False
## Practical example
has_ticket = False
is_vip = True
can_enter = has_ticket or is_vip ## True
NOT Operator
## NOT operator examples
print(not True) ## False
print(not False) ## True
## Practical example
is_weekend = False
is_workday = not is_weekend ## True
Short-Circuit Evaluation
Python uses short-circuit evaluation for logical operators:
## Short-circuit with AND
def check_positive(x):
return x > 0 and x % 2 == 0
print(check_positive(4)) ## True
print(check_positive(-2)) ## False
## Short-circuit with OR
def get_first_truthy(a, b):
return a or b or "No value"
print(get_first_truthy(0, 10)) ## 10
print(get_first_truthy("", [1,2])) ## [1,2]
Complex Conditions in LabEx Python Environment
When practicing logical operators, the LabEx platform provides an interactive environment to experiment with complex conditions.
Best Practices
- Use parentheses to clarify complex conditions
- Prefer readability over brevity
- Break complex conditions into multiple steps
## Complex condition example
def can_vote(age, is_citizen):
return age >= 18 and is_citizen
## More readable version
def advanced_voting_check(age, is_citizen, has_id):
is_age_valid = age >= 18
is_documentation_complete = is_citizen and has_id
return is_age_valid and is_documentation_complete
Key Takeaways
- Logical operators combine Boolean values
and
, or
, and not
are the primary logical operators
- Short-circuit evaluation can optimize condition checking
- Complex conditions should prioritize readability