Logical operators in Python are used to combine multiple conditions and evaluate them as a single expression. They return a Boolean value (True or False).
They are mainly used in:
if, while)Python has three logical operators:
| Operator | Name | Description |
|---|---|---|
and |
Logical AND | True if both conditions are True |
or |
Logical OR | True if at least one condition is True |
not |
Logical NOT | Reverses the result |
and)Returns True only if both conditions are True.
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
a = 10
print(a > 5 and a < 20)
print(a > 5 and a < 8)
Output
True
False
or)Returns True if at least one condition is True.
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
a = 10
print(a > 5 or a < 8)
print(a < 5 or a < 8)
Output
True
False
not)Reverses the Boolean value.
| A | not A |
|---|---|
| True | False |
| False | True |
a = 10
print(not(a > 5))
Output
False
age = 20
if age >= 18 and age <= 60:
print("Eligible")
Python uses short-circuiting:
and: stops if first condition is Falseor: stops if first condition is Trueprint(False and True) # second condition not checked
print(True or False) # second condition not checked
Logical operators can return actual values (not just True/False).
print(0 and 5)
print(5 and 10)
print(0 or 5)
print(5 or 10)
Output
0
10
5
5
username = "admin"
password = "1234"
if username == "admin" and password == "1234":
print("Login successful")
else:
print("Invalid credentials")
Logical operators are used for decision-making.
Types include:
and → both conditions must be Trueor → at least one condition must be Truenot → reverses resultUseful in if statements and loops.
Supports short-circuit evaluation.