How to Use Logical Operators in Python: Syntax and Examples
In Python, logical operators
and, or, and not combine or invert boolean values. Use and to check if both conditions are true, or if at least one is true, and not to reverse a condition's truth value.Syntax
Python has three main logical operators:
and: ReturnsTrueif both conditions are true.or: ReturnsTrueif at least one condition is true.not: Reverses the truth value of a condition.
python
result_and = condition1 and condition2 result_or = condition1 or condition2 result_not = not condition1
Example
This example shows how to use and, or, and not with simple boolean values and conditions.
python
a = True b = False print('a and b:', a and b) # Both must be True print('a or b:', a or b) # At least one is True print('not a:', not a) # Reverse of a # Using with comparisons x = 5 print('x > 3 and x < 10:', x > 3 and x < 10) # True if x is between 3 and 10 print('x < 3 or x > 10:', x < 3 or x > 10) # True if x is outside 3 to 10
Output
a and b: False
a or b: True
not a: False
x > 3 and x < 10: True
x < 3 or x > 10: False
Common Pitfalls
Common mistakes include using && or || like in other languages, which are invalid in Python. Also, mixing and/or with non-boolean values without understanding short-circuit behavior can cause unexpected results.
python
# Correct way: correct = True and False # Pitfall example: value = '' or 'default' # Returns 'default' because '' is falsey print(value)
Output
default
Quick Reference
| Operator | Description | Example | Result |
|---|---|---|---|
| and | True if both are true | True and False | False |
| or | True if at least one is true | True or False | True |
| not | Reverses the truth value | not True | False |
Key Takeaways
Use
and to require both conditions to be true.Use
or to require at least one condition to be true.Use
not to reverse a condition's truth value.Avoid using
&& or || as they cause syntax errors in Python.Remember Python's logical operators can work with any values, not just booleans, using truthy and falsey rules.