What Are Logical Operators in Python?
Logical operators in Python are keywords that allow you to combine or modify conditional expressions and evaluate whether the overall condition is True or False. These operators are essential for decision-making and controlling the flow in your programs.
Types of Logical Operators
Python has three main logical operators:
| Operator | Meaning |
|---|---|
and | True if both conditions are true |
or | True if at least one condition is true |
not | Reverses the truth value (True → False, False → True) |
How Logical Operators Work (Input & Output)
1. Logical AND (and)
Returns True only if all conditions are True
print(True and True) print(True and False) print(5 > 3 and 2 < 4) # Output: # True # False # True-
True and True→ True -
If any condition is False, the result is False.
2. Logical OR (or)
Returns True if at least one condition is True
print(True or False) print(False or False) print(5 > 10 or 2 < 4) # Output: # True # False # True-
True or False→ True -
Only
False or False→ False.
3. Logical NOT (not)
Reverses the truth value:
print(not True) print(not False) print(not (5 > 10)) # Output: # False # True # True -
not Truebecomes False -
not Falsebecomes True.
Using Logical Operators with Variables
age = 18 has_id = True print(age >= 18 and has_id) print(age < 18 or has_id) print(not (age < 18)) # Output: # True # True # True and, or, and not help combine multiple boolean expressions.
Short-Circuit Evaluation
Python uses short-circuit logic with and and or, meaning evaluation stops as soon as the result is determined:
-
For
and: if the first condition is False, Python doesn’t evaluate the second. -
For
or: if the first condition is True, Python doesn’t evaluate the second.
This behavior can improve performance and avoid unnecessary evaluation.
Logical Operators in Conditional Statements
Logical operators are often used in if statements
temp = 25 is_sunny = True if temp > 20 and is_sunny: print("Perfect day for a walk!") # Output: # Perfect day for a walk! This runs the print statement only if both conditions are True.
Truth Table
| 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 |