4. Logical Operators
Logical operators are used to combine multiple conditions and return a True or False result based on logical evaluation.
They are mostly used in if or while statements to make decisions.
Types of Logical Operators
- and – Returns True if both conditions are True
- or – Returns True if at least one condition is True
- not – Reverses the result (True becomes False, and vice versa)
List of Logical Operators
Operator | Name | Description | Example |
---|---|---|---|
and |
Logical AND | Returns True only if both conditions are true |
(5 > 3 and 8 > 2) → True |
or |
Logical OR | Returns True if at least one condition is true |
(5 < 3 or 8 > 2) → True |
not |
Logical NOT | Reverses the result: True becomes False and vice versa
|
not(5 > 3) → False |
Examples of Logical Operators in Python
1. Logical AND (and
)
The result is True
only when both conditions are True.
a = 5
b = 10
print(a > 3 and b > 7) # True
print(a > 6 and b > 7) # False
Output:
True
False
Explanation:
a > 3
is True, andb > 7
is True → Truea > 6
is False, andb > 7
is True → False
2. Logical OR (or
)
The result is True
if any one condition is True.
x = 4
y = 8
print(x < 5 or y < 3) # True
print(x > 6 or y < 2) # False
Output:
True
False
Explanation:
x < 5
is True,y < 3
is False → One is True → Truex > 6
is False,y < 2
is also False → Both False → False
3. Logical NOT (not
)
The result is the opposite of the actual condition.
p = 7
print(not(p > 3)) # False
print(not(p < 3)) # True
Output:
False
True
Explanation:
p > 3
is True →not(True)
= Falsep < 3
is False →not(False)
= True
Note: Logical operators always return a boolean result (True or False).
Using with Conditions
You can combine multiple comparisons in if statements using logical operators:
age = 25
citizen = True
if age >= 18 and citizen:
print("You can vote.")
else:
print("You are not eligible.")
Here, age >= 18 and citizen both must be True for the message to be printed.
Summary
- and – All conditions must be True
- or – At least one condition should be True
- not – Flips the result (True ↔ False)
- Returns: True or False
- Used inside if, while, etc. for decision making