π Pythonπ
Day 5
Operators in Python
Arithmetic, comparison, logical, assignment, identity and membership operators.
π―
Learning objectives
- βUse arithmetic and comparison operators fluently
- βUnderstand and, or, not vs & | ~
- βApply is vs == correctly
π‘ Key points
- Two divisions: / gives float, // gives floor int.
- ** is exponent (2 ** 10 = 1024).
- and / or / not are English keywords β not && || ! .
- == compares values. is compares identity (same object in memory).
- in tests membership: `'a' in 'abc'`, `3 in [1,2,3]`.
π» Code examples(4)
#1Arithmetic
pythonprint(7 / 2) # 3.5 (true division)
print(7 // 2) # 3 (floor division)
print(7 % 2) # 1 (modulo)
print(2 ** 10) # 1024 (power)
print(-7 // 2) # -4 (floors DOWN, not towards zero!)
// floors towards negative infinity. -7 // 2 = -4, not -3.
#2Comparison + chaining
pythonx = 5
print(1 < x < 10) # True β chained comparison
print(x == 5 != 6) # True
# equivalent long form:
print(1 < x and x < 10)
Python allows chained comparisons β no need for `and`. Reads like math.
#3Logical operators
pythona, b = True, False
print(a and b) # False
print(a or b) # True
print(not a) # False
# short-circuit + return actual operand
print(0 or "default") # "default"
print("x" and "y") # "y"
and/or return one of the operands, not just True/False. Idiom: `name = user_input or 'guest'`.
#4is vs ==
pythona = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True β same contents
print(a is b) # False β different objects
print(a is c) # True β same object
== checks value equality. is checks identity (memory address). Use `is` only with None: `if x is None:`
π― Practice
Q1. What is 5 ** 0.5 ?+
2.23606... (square root of 5). ** works with fractional exponents too.
Q2. Difference between and and & ?+
and is logical (short-circuit, returns operand). & is bitwise (works on integers or NumPy arrays). Don't confuse them.
Q3. How to check if a key exists in a dict?+
if key in my_dict: ... # uses the 'in' membership operator, O(1) for dicts.
π Notes
Walrus operator (Python 3.8+)
Assign inside an expression:
if (n := len(data)) > 10:
print(f"Long input: {n} items")
Handy for while loops that read + test in one line:
while chunk := file.read(1024):
process(chunk)
Operator precedence β top to bottom
| Level | Operator |
|---|---|
| Highest | ** |
| | unary +x, -x, ~x |
| | * / // % |
| | + - |
| | < <= > >= != == in not in is is not |
| | not |
| | and |
| Lowest | or |
Use parentheses when in doubt.