Python Operators

Tutorial 9 of 65 · pythondeck.com Python course

Python provides arithmetic (+ - * / // % **), comparison (== != < > <= >=), logical (and or not), bitwise (& | ^ ~ << >>), assignment (= += -= *=...), membership (in, not in) and identity (is, is not) operators. Operator precedence follows mathematics; use parentheses to be explicit.

Operators express computations and comparisons on objects. Python overloads them per type via special methods (__add__, __eq__), so the same symbol means different things for numbers, strings, and sets.

Precedence and associativity determine evaluation order; parentheses clarify intent when mixing arithmetic, bitwise, logical, and comparison operators.

Arithmetic: + - * / // % **; unary -; matrix @ with NumPy.

Comparison: == != < > <= >=; chaining supported.

Logical: and or not; bitwise: & | ^ ~ << >> on integers.

Assignment: = and augmented += -= *= etc.

Membership and identity: in, not in, is, is not.

Walrus := assigns inside expressions (3.8+).

For custom classes, implement dunder methods sparingly so + and == behave predictably. __eq__ without __hash__ makes instances unhashable.

Operator overloading does not change truthiness; define __bool__ if instances should behave in if obj:.

The operator module and chained comparisons (a < b < c) keep expressions readable and efficient.

Confusing is with == for value comparison.

Bitwise & where you meant logical and between conditions.

Forgetting that ** binds tighter than unary minus: -3**2 is -9.

Using + to merge dicts in old code—prefer | merge (3.9+) or .update.

Parenthesize complex expressions; do not depend on memorizing every precedence level.

Use math or decimal for numeric stability instead of clever operator tricks.

Prefer readable names over cramming logic into one expression with walrus unless it aids clarity.

Test edge cases for division by zero and modulo with negatives.

Use parentheses when mixing and with comparisons so intent matches evaluation order.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates arithmetic. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Arithmetic
# Run in the REPL or save as a .py file and execute with python.
print(7 / 2, 7 // 2, 7 % 2, 7 ** 2)

This sample walks through bitwise in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: Bitwise
# Run in the REPL or save as a .py file and execute with python.
print(0b1100 & 0b1010)   # 0b1000 = 8
print(0b1100 | 0b1010)   # 0b1110 = 14
print(1 << 4)            # 16

Here is a hands-on illustration of membership. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Membership
# Run in the REPL or save as a .py file and execute with python.
names = ["Ada", "Linus", "Grace"]
print("Ada" in names)
print("Tim" not in names)

The program below demonstrates bitwise masks. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Bit operators work on integer bit patterns
flags = 0b1010  # binary literal for ten
mask = 0b0011  # low two bits
print(flags & mask)  # AND keeps overlapping 1 bits -> 2
print(flags | 0b0101)  # OR sets bits -> 15
print(flags ^ 0b1111)  # XOR toggles bits
print(flags << 1)  # left shift doubles value -> 20
print(flags >> 1)  # right shift halves -> 5
print(~0 & 0xFF)  # invert then mask to byte -> 255
power = 2 ** 10  # exponentiation operator
print(power)  # 1024

This sample walks through walrus demo in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# := assigns inside an expression (3.8+)
data = [1, 3, 5, 7, 9, 11]  # odd numbers
while (n := len(data)) > 3:  # assign length then compare
    data.pop()  # shrink list until length <= 3
print(n, data)  # final length and contents
text = "hello world"  # sample string
if (idx := text.find("world")) >= 0:  # assign index if found
    print("found at", idx)  # 6
items = [1, 2, 3, 4]  # list for comprehension
squares = [y for x in items if (y := x * x) > 4]  # walrus in comp
print(squares)  # [9, 16]

« Python Booleans All tutorials Python Lists »