Logical operators are used to combine conditional statements. Python has three logical operators:
- and - Returns True if both statements are true
- or - Returns True if one of the statements is true
- not - Reverses the result, returns False if the result is true
The and Operator
The and keyword is a logical operator, and is used to combine conditional statements. Both conditions must be true for the entire expression to be true.
aThe or Operator
The or keyword is a logical operator, and is used to combine conditional statements. At least one condition must be true for the entire expression to be true.
aThe not Operator
The not keyword is a logical operator, and is used to reverse the result of the conditional statement.
aCombining Multiple Operators
You can combine multiple logical operators in a single expression. Python evaluates not first, then and , then or .
andTruth Tables
Understanding how logical operators work with different values:
and Operator Truth Table
| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
or Operator Truth Table
| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
Using Parentheses for Clarity
When combining multiple logical operators, use parentheses to make your intentions clear and control the order of evaluation.
Example
temperature = 25
is_raining = False
is_weekend = True
if (temperature > 20 and not is_raining) or is_weekend:
print("Great day for outdoor activities!")