Operators
Operators are the symbols that combine values. You have already used several; this lesson collects all of them in one place.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide | 7 / 2 | 3.5 |
// | Floor divide | 7 // 2 | 3 |
% | Modulo | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
print(7 + 2, 7 - 2, 7 * 2, 7 / 2, 7 // 2, 7 % 2, 7 ** 2)Modulo is the standard way to test divisibility: n % 2 == 0 means n is even.
Assignment operators
Every arithmetic operator has a shorthand that updates a variable in place.
x = 10
x += 5 # x = x + 5
x -= 3 # x = x - 3
x *= 2 # x = x * 2
x //= 4 # x = x // 4
x **= 2 # x = x ** 2
print(x)Comparison operators
These return booleans.
a, b = 5, 8
print(a == b, a != b)
print(a < b, a <= b)
print(a > b, a >= b)Comparisons can be chained the way you would write them in maths:
n = 15
print(1 <= n <= 20)Logical operators
print(True and False)
print(True or False)
print(not True)Membership operators
in and not in test whether a value is inside a collection or a substring is inside a string.
print(3 in [1, 2, 3])
print("x" not in "python")
print("name" in {"name": "Ira", "age": 22}) # checks keysIdentity operators
is tests whether two names refer to the same object, not whether their values are equal.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # same contents
print(a is b) # different objects
print(a is c) # same objectUse is only for None, True and False. Use == for everything else.
Bitwise operators
These work on the binary representation of integers. You will meet them in low level code and in NumPy or pandas boolean masks.
print(6 & 3) # AND 110 & 011 = 010
print(6 | 3) # OR 110 | 011 = 111
print(6 ^ 3) # XOR 110 ^ 011 = 101
print(~6) # NOT -7
print(1 << 3) # shift left, 8
print(16 >> 2) # shift right, 4Operator precedence
From highest to lowest:
**- unary
-,+,~ *,/,//,%+,-- comparisons,
in,is notandor
When in doubt, add parentheses. They cost nothing and make intent obvious.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(-2 ** 2) # -(2 ** 2) = -4
print((-2) ** 2)The walrus operator
:= assigns and returns a value in one expression. It is useful when you need a value both in a condition and inside the block.
data = [4, 8, 15, 16, 23, 42]
if (n := len(data)) > 5:
print(f"List is long: {n} items")Practice
- Use
%and//to split 367 seconds into minutes and seconds. - Write a single expression that checks whether a year is a leap year.
- Explain why
2 ** 3 ** 2gives 512 and not 64, then verify.
