indusai.co

Operators

Operators are the symbols that combine values. You have already used several; this lesson collects all of them in one place.

Arithmetic operators

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide7 / 23.5
//Floor divide7 // 23
%Modulo7 % 21
**Power7 ** 249
python
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.

python
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.

python
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:

python
n = 15
print(1 <= n <= 20)

Logical operators

python
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.

python
print(3 in [1, 2, 3])
print("x" not in "python")
print("name" in {"name": "Ira", "age": 22})   # checks keys

Identity operators

is tests whether two names refer to the same object, not whether their values are equal.

python
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 object

Use 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.

python
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, 4

Operator precedence

From highest to lowest:

  1. **
  2. unary -, +, ~
  3. *, /, //, %
  4. +, -
  5. comparisons, in, is
  6. not
  7. and
  8. or

When in doubt, add parentheses. They cost nothing and make intent obvious.

python
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.

python
data = [4, 8, 15, 16, 23, 42]
if (n := len(data)) > 5:
    print(f"List is long: {n} items")

Practice

  1. Use % and // to split 367 seconds into minutes and seconds.
  2. Write a single expression that checks whether a year is a leap year.
  3. Explain why 2 ** 3 ** 2 gives 512 and not 64, then verify.