Python Logical Operators
Logical operators are used to combine conditional statements and return Boolean values (True or False). They are fundamental in controlling the flow of a program by evaluating multiple conditions.
Python has three logical operators:
| Operator |
Description |
Example |
and |
Logical AND |
Returns True if both conditions are True |
or |
Logical OR |
Returns True if at least one condition is True |
not |
Logical NOT (negation) |
Reverses the Boolean value |
1. and Operator
The and operator returns True only if both conditions are True. If either one or both are False, it returns False.
Syntax:
condition1 and condition2
Example:
x = 10
print(x > 5 and x < 15) # True, because 10 > 5 AND 10 < 15
print(x > 5 and x > 20) # False, second condition is False
Explanation:
x > 5 and x < 15 is True because both parts are true.
x > 5 and x > 20 is False because the second part (x > 20) is false.
2. or Operator
The or operator returns True if at least one of the conditions is True. It only returns False if both conditions are False.
Syntax:
condition1 or condition2
Example:
x = 10
print(x > 5 or x > 20) # True, because first condition is True
print(x < 5 or x > 20) # False, both conditions are False
Explanation:
x > 5 or x > 20 is True because x > 5 is true.
x < 5 or x > 20 is False because both conditions are false.
3. not Operator
The not operator reverses the Boolean value of a condition.
Syntax:
not condition
Example:
x = 10
print(not x > 5) # False, because x > 5 is True, and `not` reverses it
print(not x < 5) # True, because x < 5 is False, and `not` reverses it
Combining Logical Operators
You can combine and, or, and not to form complex conditions.
Example:
x = 10
y = 20
if x > 5 and (y < 15 or not y == 20):
print("Condition met")
else:
print("Condition not met")
Explanation:
x > 5 is True
y < 15 is False
not y == 20 means not True → False
(y < 15 or not y == 20) → False or False → False
- So
True and False → False, so the else block runs.
Truth Table Summary
| A |
B |
A and B |
A or B |
not A |
| True |
True |
True |
True |
False |
| True |
False |
False |
True |
False |
| False |
True |
False |
True |
True |
| False |
False |
False |
False |
True |