Skip to content

Python Operators: Arithmetic, Comparison, Logical, and Bitwise

  • Arithmetic operators, including the difference between /, //, and %.
  • Comparison operators and why Python lets you chain them.
  • Logical operators and how short-circuit evaluation works.
  • Bitwise operators for working with flags and binary values.
  • Augmented assignment operators.
  • Identity (is) vs equality (==) and when each matters.
  • Membership tests with in and not in.
  • Operator precedence and the walrus operator :=.
  • Python 3.9 or newer installed (python --version).
  • Familiarity with integers, floats, and basic data structures.

Every expression in Python is built from operators. Some, like + and ==, are familiar from school math; others, like //, is, and :=, are specific to Python. This tutorial walks through each family in the order you are most likely to meet them, using values from the OrdersPortal order system. Understanding operator precedence and the distinction between value equality and object identity will prevent the most common bugs in everyday code.

Python has the usual arithmetic operators plus floor division, modulo, and exponentiation. / always returns a float even when both operands are integers, which is the most common surprise for people coming from other languages. // divides and drops the fractional part, but it still returns a float if either operand is a float. % returns the remainder, and ** raises to a power.

qty, price = 7, 19.99
print(qty * price) # 139.93 — multiplication
print(price + 5.00) # 24.99 — addition
print(price - 2.00) # 17.99 — subtraction
print(100 / 4) # 25.0 — true division (always float)
print(100 // 4) # 25 — floor division
print(100 / 7) # 14.285714285714286
print(100 // 7) # 14 — floor division drops the fraction
print(100 % 7) # 2 — modulo: 100 = 14*7 + 2
print(2 ** 10) # 1024 — exponentiation

Verify: Compute (100 // 7) * 7 + (100 % 7). The result should equal 100, which confirms floor division and modulo are consistent.

Comparison operators return True or False, and they work on any comparable types. Unlike many languages, Python lets you chain comparisons, so a < b < c means a < b and b < c, evaluated once each with no risk of b being evaluated twice. Equality compares values; == does not check that two objects are the same object.

amount = 149.99
print(amount == 149.99) # True — equal
print(amount != 100.00) # True — not equal
print(amount < 200.00) # True — less than
print(amount > 200.00) # False — greater than
print(amount >= 149.99) # True — greater than or equal
print(amount <= 149.99) # True — less than or equal
# Chained comparison — "is the total between 50 and 200?"
print(50 <= amount <= 200) # True

Verify: Compare two floats that should be equal but were computed differently, such as 0.1 + 0.2 == 0.3. It prints False due to binary floating point, which is a reminder to compare money with decimal or a tolerance.

and, or, and not work on truthiness, not just on bool. They short-circuit: and stops at the first false operand and returns it, or stops at the first true operand and returns it. Because they return an operand rather than a hard True/False, they are handy for defaults and guards.

status = None
# 'or' returns the first truthy operand — a default value
display = status or "unknown"
print(display) # unknown
# 'and' returns the last operand if all are truthy
print(10 and 20) # 20
# Short-circuit prevents an error when the left side is falsy
order = None
print(order and order["id"]) # None — order["id"] is never evaluated
# 'not' inverts truthiness
print(not []) # True — empty list is falsy
print(not "ok") # False

Verify: Set order = {"id": "ORD-001"} and rerun the and line. It should print ORD-001, confirming the right operand was reached and returned.

Bitwise operators work on the binary representation of integers. They are uncommon in application code but appear with permission flags, compact status masks, and low-level protocols. & is AND, | is OR, ^ is XOR, ~ is bitwise NOT (which negates and flips the sign), << shifts left, and >> shifts right. Use parentheses generously; bitwise operators bind more loosely than you might expect.

# OrdersPortal permission flags as bits
READ, WRITE, DELETE = 1, 2, 4 # 0b001, 0b010, 0b100
perm = READ | WRITE # 0b011 = 3 — combine flags
print(perm) # 3
print(perm & READ) # 1 — has READ?
print(perm & DELETE) # 0 — does not have DELETE
print(perm ^ WRITE) # 1 — toggle WRITE off (XOR)
print(~perm) # -4 — bitwise NOT inverts all bits
print(perm << 1) # 6 — shift left doubles the value
print(perm >> 1) # 1 — shift right halves it (floor)

Verify: Build a mask READ | WRITE | DELETE and check mask & DELETE is 4, confirming all three flags are present.

Step 5 — Assignment and augmented assignment

Section titled “Step 5 — Assignment and augmented assignment”

= binds a name to a value. The augmented operators (+=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=) update a name in place. For immutable types like int this is just shorthand for x = x op y, but for mutable types like lists the in-place operators call methods such as list.__iadd__ that extend the original object instead of rebinding.

total = 100
total += 50 # 150 — total = total + 50
total -= 20 # 130
total *= 2 # 260
total /= 10 # 26.0 — division returns float
total //= 3 # 8.0
total %= 3 # 2.0
# Multiple assignment and swap without a temp variable
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1

Verify: After the swap, a should be 2 and b should be 1, confirming the tuple-pack-and-unpack swap worked without a temporary variable.

is checks whether two names refer to the exact same object in memory, not whether they hold equal values. Use is mainly for the singletons None, True, and False. For value comparison, use ==. Membership operators in and not in test whether a value appears in a container; on a dict they check keys, and on a string they check substrings.

a = [1, 2]
b = a
c = [1, 2]
print(a == c) # True — same values
print(a is c) # False — different objects
print(a is b) # True — same object
print(a is not c) # True
status = None
print(status is None) # True — the correct way to test for None
order_ids = ["ORD-001", "ORD-002", "ORD-003"]
print("ORD-002" in order_ids) # True
print("ORD-009" not in order_ids) # True
order = {"id": "ORD-001", "status": "pending"}
print("status" in order) # True — 'in' checks keys, not values
print("pending" in order) # False
print("ORD" in "ORD-001") # True — substring search

Verify: Comparing a is c returns False even though a == c is True, which shows that is tests identity, not equality.

Step 7 — Precedence and the walrus operator

Section titled “Step 7 — Precedence and the walrus operator”

Operators bind with a fixed precedence, and you can override any of it with parentheses. When in doubt, add parentheses: they cost nothing at runtime and make intent obvious. The walrus operator := (PEP 572, Python 3.8+) assigns a name and returns the value in one expression, which is handy inside if conditions and while loops to avoid calling a function twice.

# Precedence: ** binds tighter than unary minus
print(-2 ** 2) # -4 — it's -(2**2), not (-2)**2
print((-2) ** 2) # 4 — parentheses make intent explicit
# Walrus: assign and test in one expression
order = {"id": "ORD-001"}
if (oid := order.get("tracking")):
print(f"Tracking: {oid}")
else:
print("No tracking number")
# No tracking number

Operator precedence, high to low: ** → unary + - ~ → * / // % → + - → << >> → & → ^ → | → comparisons and in/is → not → and → or.

Verify: Print -2 ** 2 and (-2) ** 2. The different results confirm precedence binds ** more tightly than the unary minus.

Save as operators_demo.py and run with python operators_demo.py (Python 3.9+):

"""OrdersPortal: apply a discount, split an order across items, and check flags."""
subtotal = 149.99
discount_rate = 0.10 # 10% off
line_count = 3
flags = {"paid", "packed"}
# Arithmetic and augmented assignment
discount = round(subtotal * discount_rate, 2)
total = subtotal - discount # 134.99
total += 5.00 # shipping
print(f"Total: {total}") # Total: 139.99
# Division and modulo to split items evenly
per_line = total // line_count # 46.0
remainder = round(total % line_count, 2) # 1.99 — round for clean money output
print(f"Per line: {per_line}, remainder: {remainder}")
# Comparison and chained check
print("Eligible for free shipping?", 100.00 <= total <= 150.00) # True
# Logical short-circuit for a default carrier
carrier = None
print("Carrier:", carrier or "StandardPost") # Carrier: StandardPost
# Membership tests on the flag set
print("Is paid?", "paid" in flags) # True
print("Is shipped?", "shipped" in flags) # False
# Walrus: read a value and act on it in one step
if (note := "Gift wrap requested"):
print(f"Note: {note}") # Note: Gift wrap requested
Total: 139.99
Per line: 46.0, remainder: 1.99
Eligible for free shipping? True
Carrier: StandardPost
Is paid? True
Is shipped? False
Note: Gift wrap requested
  • Using is to compare values. is tests identity, so a is 256 may be True but a is 257 may be False because of integer caching. Use == for value comparisons.
  • Comparing floats with == for money. Binary floating point makes 0.1 + 0.2 == 0.3 false. Use the decimal module or compare with a tolerance.
  • Confusing / and //. / always returns a float; // floors toward negative infinity, so -7 // 2 is -4, not -3.
  • Forgetting and/or return an operand. 0 or 0 is 0, not False. When you need a strict boolean, wrap with bool(...).
  • Relying on precedence without parentheses. -2 ** 2 is -4, not 4. Add parentheses whenever the intent could be misread.
  • Lists — membership and augmented assignment in practice
  • Dictionaries — in checks keys, not values
  • Sets — fast membership tests and set math with operators
  • Type hints — annotating the values operators produce