Logical
- Python course
- Beginner
- Lesson 26/116
- 4 min
Learn boolean logic with and, or, not.
Logical operators
Logical operators combine bool values: and, or, not.
print(True and False) # False
print(True or False) # True
print(not True) # Falseand gives True only when both sides are True. or gives True when at least one side is True. not flips the value.
These operators are common in conditions: if age >= 18 and has_id:
Short circuit
Logical operators short circuit: when the result is determined, the other side is not evaluated.
False and expensive() # expensive not called
True or expensive() # expensive not calledFalse and ... is already False, the right side does not run. True or ... is already True, the right side does not run. This is useful for performance and safety.
Practice Print logical operations
Assign age = 20 and has_id = True. Print print(age >= 18 and has_id).
Starter code
# Logical operationsSample solution
age = 20
has_id = True
print(age >= 18 and has_id)Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the logical operator
print(True ____ False)
print(True and False)
Explanation: and gives True when both sides are True.
2 What is True or False?
- Error
- False
- True Correct answer
- None
Explanation: or gives True when at least one is True.
3 Match the logical operators
| Term | Meaning |
|---|---|
and |
Both True |
or |
At least one True |
not |
Flips |
True |
True |