Python Operators: Arithmetic, Comparison, Logical, and Bitwise
What you’ll learn
Section titled “What you’ll learn”- 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
inandnot in. - Operator precedence and the walrus operator
:=.
Prerequisites
Section titled “Prerequisites”- 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.
Step 1 — Arithmetic operators
Section titled “Step 1 — Arithmetic operators”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 — multiplicationprint(price + 5.00) # 24.99 — additionprint(price - 2.00) # 17.99 — subtractionprint(100 / 4) # 25.0 — true division (always float)print(100 // 4) # 25 — floor divisionprint(100 / 7) # 14.285714285714286print(100 // 7) # 14 — floor division drops the fractionprint(100 % 7) # 2 — modulo: 100 = 14*7 + 2print(2 ** 10) # 1024 — exponentiationVerify: Compute (100 // 7) * 7 + (100 % 7). The result should equal 100, which confirms floor division and modulo are consistent.
Step 2 — Comparison operators
Section titled “Step 2 — Comparison operators”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 — equalprint(amount != 100.00) # True — not equalprint(amount < 200.00) # True — less thanprint(amount > 200.00) # False — greater thanprint(amount >= 149.99) # True — greater than or equalprint(amount <= 149.99) # True — less than or equal
# Chained comparison — "is the total between 50 and 200?"print(50 <= amount <= 200) # TrueVerify: 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.
Step 3 — Logical operators
Section titled “Step 3 — Logical operators”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 valuedisplay = status or "unknown"print(display) # unknown
# 'and' returns the last operand if all are truthyprint(10 and 20) # 20
# Short-circuit prevents an error when the left side is falsyorder = Noneprint(order and order["id"]) # None — order["id"] is never evaluated
# 'not' inverts truthinessprint(not []) # True — empty list is falsyprint(not "ok") # FalseVerify: Set order = {"id": "ORD-001"} and rerun the and line. It should print ORD-001, confirming the right operand was reached and returned.
Step 4 — Bitwise operators
Section titled “Step 4 — Bitwise operators”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 bitsREAD, WRITE, DELETE = 1, 2, 4 # 0b001, 0b010, 0b100
perm = READ | WRITE # 0b011 = 3 — combine flagsprint(perm) # 3print(perm & READ) # 1 — has READ?print(perm & DELETE) # 0 — does not have DELETEprint(perm ^ WRITE) # 1 — toggle WRITE off (XOR)print(~perm) # -4 — bitwise NOT inverts all bitsprint(perm << 1) # 6 — shift left doubles the valueprint(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 = 100total += 50 # 150 — total = total + 50total -= 20 # 130total *= 2 # 260total /= 10 # 26.0 — division returns floattotal //= 3 # 8.0total %= 3 # 2.0
# Multiple assignment and swap without a temp variablea, b = 1, 2a, b = b, aprint(a, b) # 2 1Verify: After the swap, a should be 2 and b should be 1, confirming the tuple-pack-and-unpack swap worked without a temporary variable.
Step 6 — Identity vs membership
Section titled “Step 6 — Identity vs membership”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 = ac = [1, 2]
print(a == c) # True — same valuesprint(a is c) # False — different objectsprint(a is b) # True — same objectprint(a is not c) # True
status = Noneprint(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) # Trueprint("ORD-009" not in order_ids) # True
order = {"id": "ORD-001", "status": "pending"}print("status" in order) # True — 'in' checks keys, not valuesprint("pending" in order) # Falseprint("ORD" in "ORD-001") # True — substring searchVerify: 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 minusprint(-2 ** 2) # -4 — it's -(2**2), not (-2)**2print((-2) ** 2) # 4 — parentheses make intent explicit
# Walrus: assign and test in one expressionorder = {"id": "ORD-001"}
if (oid := order.get("tracking")): print(f"Tracking: {oid}")else: print("No tracking number")# No tracking numberOperator 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.
Complete working example
Section titled “Complete working example”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.99discount_rate = 0.10 # 10% offline_count = 3flags = {"paid", "packed"}
# Arithmetic and augmented assignmentdiscount = round(subtotal * discount_rate, 2)total = subtotal - discount # 134.99total += 5.00 # shippingprint(f"Total: {total}") # Total: 139.99
# Division and modulo to split items evenlyper_line = total // line_count # 46.0remainder = round(total % line_count, 2) # 1.99 — round for clean money outputprint(f"Per line: {per_line}, remainder: {remainder}")
# Comparison and chained checkprint("Eligible for free shipping?", 100.00 <= total <= 150.00) # True
# Logical short-circuit for a default carriercarrier = Noneprint("Carrier:", carrier or "StandardPost") # Carrier: StandardPost
# Membership tests on the flag setprint("Is paid?", "paid" in flags) # Trueprint("Is shipped?", "shipped" in flags) # False
# Walrus: read a value and act on it in one stepif (note := "Gift wrap requested"): print(f"Note: {note}") # Note: Gift wrap requestedTotal: 139.99Per line: 46.0, remainder: 1.99Eligible for free shipping? TrueCarrier: StandardPostIs paid? TrueIs shipped? FalseNote: Gift wrap requestedCommon mistakes
Section titled “Common mistakes”- Using
isto compare values.istests identity, soa is 256may beTruebuta is 257may beFalsebecause of integer caching. Use==for value comparisons. - Comparing floats with
==for money. Binary floating point makes0.1 + 0.2 == 0.3false. Use thedecimalmodule or compare with a tolerance. - Confusing
/and//./always returns a float;//floors toward negative infinity, so-7 // 2is-4, not-3. - Forgetting
and/orreturn an operand.0 or 0is0, notFalse. When you need a strict boolean, wrap withbool(...). - Relying on precedence without parentheses.
-2 ** 2is-4, not4. Add parentheses whenever the intent could be misread.
Next steps
Section titled “Next steps”- Variables and data types — what operators operate on
- Conditionals — using comparison and logical operators in
if - Walrus operator — assignment expressions in depth
Related pages
Section titled “Related pages”- Lists — membership and augmented assignment in practice
- Dictionaries —
inchecks keys, not values - Sets — fast membership tests and set math with operators
- Type hints — annotating the values operators produce