Logical Operators
Python · Operators
Theory
Logical operators combine conditions: and is true only when both sides are true, or is true when at least one side is true, and not flips a value. age >= 18 and country == 'IN' is True only when both checks pass. Precedence is not first, then and, then or, so a or b and c means a or (b and c); add parentheses to make intent clear.
Two details make Python special. First, and and or short-circuit: they stop as soon as the answer is known, so in x != 0 and 10 / x > 1 the division never runs when x is 0. Second, they return one of the original operands, not necessarily True or False: 0 or 'default' returns 'default', and 3 and 4 returns 4. This powers idioms like name = user_input or 'Guest'. Do not confuse them with & and |, which are bitwise operators.
Why we use it
Real rules rarely depend on one check. Logical operators let you express 'adult AND in India' or 'VIP OR order above 5000' in one readable expression, and short-circuiting lets you guard risky checks safely.
When to use it
Use and/or/not in if and while conditions with plain Python values. Use & and | (with parentheses around each condition) for pandas or NumPy boolean masks instead, because and/or do not work element-wise on columns.
How it works
- Evaluate A and B
- Evaluate A first
- Is A falsy? Yes: Return A immediately; B never runs. No: Evaluate B and return it.
- For A or B: if A is truthy return A, else evaluate and return B
- not A always returns a real True or False
Syntax
expr1 and expr2
expr1 or expr2
not exprExample
age = 20
country = "IN"
print(age >= 18 and country == "IN")Key points
- and/or short-circuit: the second expression may not even run
- not inverts a boolean value
- Precedence: not, then and, then or
- They return an operand: 0 or 'default' gives 'default'
- Use & and | for pandas masks, not and/or