Lesson · Language Fundamentals
Operators
60 min readOperators
Operators are method-driven syntax for arithmetic, comparison, Boolean logic, bit operations, membership, and identity. The key is to understand both precedence and the meaning defined by operand types.
Learning goals
- Evaluate
+,//,%, and**on positive and negative operands, and explain why//rounds toward negative infinity. - Predict which operand an
andororexpression returns, and say when the result is not abool. - Use
inandiscorrectly, and explain whyisis not a value comparison. - Read a chained comparison such as
0 < y < xand say how many times each operand is evaluated. - Group a mixed expression by precedence, then add parentheses where a human reader needs them.
Mental model
Operators are ordinary objects responding to syntax: x + y asks the left operand's type to add, so the same symbol can mean addition, concatenation, repetition, or a custom operation. Two nested questions decide every expression: which parts group first, through precedence and chaining, and what the operand types do when the grouped operation runs.
Core idea
An operator is a request sent to its left operand's type, so meaning comes from objects rather than from the symbol, with + adding numbers, concatenating strings, and doing whatever a type you write yourself defines. Precedence and chaining decide how the parts group, and short-circuit operators and chained comparisons then evaluate only what they must.
Arithmetic operators
Arithmetic operators delegate to numeric or user-defined special methods. The same syntax can have different meanings for different operand types, such as + for numbers, strings, and lists.
Floor division
// performs floor division: the result is rounded toward negative infinity, not merely truncated toward zero. This distinction matters for negative operands.
Modulo
% returns the remainder paired with Python's floor-division rule. For a positive divisor, the result is non-negative even when the dividend is negative.
Exponentiation
** performs exponentiation and binds more tightly than unary minus on its left side. pow() provides related functionality and supports modular exponentiation for integers.
Comparison operators
Comparison operators produce Boolean results and can delegate to type-specific rich comparison methods. Equality and ordering are separate capabilities.
Boolean operators
and, or, and not implement Boolean control logic. and and or short-circuit and return one of their operands rather than always returning a bool.
Bitwise operators
Bitwise operators manipulate integer bit patterns with &, |, ^, ~, <<, and >>. They are also overloadable by user-defined types.
Membership operators
in and not in ask a container or iterable whether a value is present. Efficient containers can implement membership without scanning every element.
Identity operators
The identity operators is and is not test whether two names reference the same object, not whether two values are equal. Reserve them for singletons such as None and for cases where shared identity is the actual question; for ordinary numbers, strings, and containers, == is the value comparison you want.
Assignment expressions
The := operator evaluates an expression and binds its value as part of a larger expression. Use it when avoiding duplicate work improves clarity, not merely to make code shorter.
Operator precedence
Precedence determines how an expression groups when parentheses are omitted. Parentheses are still valuable when they make human intent clearer even if the parser does not require them.
Chained comparisons
Python can chain comparisons such as a < b < c without evaluating the middle expression twice. The chain is conceptually an and of adjacent comparisons with single evaluation of shared operands.
Walkthrough
x + yasks theinttype to add and prints13;x // y, x % yprints3 1, the quotient and remainder that satisfy(x // y) * y + x % y == x.x ** yprints1000;**binds more tightly than unary minus, so-2 ** 2groups as-(2 ** 2)and prints-4.0 < y < xis a chained comparison: it checks0 < 3and3 < 10withyevaluated once, and printsTrue.y in [1, 2, 3]asks the list whether a value equal to3is present and printsTrue;x is yasks whether both names point at one object and printsFalse, because10and3are different int objects.- Predict before running: every printed line, and what the first four prints become if
yis rebound to-3.
Experiments to try
- Rebind
y = -3and rerun the first four prints; record//and%and check both against(x // y) * y + x % y == x. - Replace
0 < y < xwith0 < y and y < xand confirm the same result; then explain the one evaluation difference, which matters when the middle operand is expensive to compute. - Evaluate
"ab" * 3,[1, 2] + [3], and2 * "ab"; then write the rule for what*and+mean when an operand is a sequence. - Try
y in "123"and read theTypeError, then try"3" in "123"and explain why membership in a string looks for a substring rather than an integer.
Common mistakes
- Assuming
//truncates toward zero: it floors toward negative infinity, so-7 // 2is-4, and the remainder from%then stays non-negative for a positive divisor. - Expecting
andandorto returnTrueorFalse: they return one of their operands, so0 or "x"gives"x", and code that needs a strict Boolean wraps the result inbool(...). - Using
isfor value comparison:istests identity, and interned numbers or strings can make it accidentally work in small cases;==is the comparison for values. - Forgetting how tightly
**binds:-2 ** 2groups as-(2 ** 2)and prints-4, so write(-2) ** 2when the sign belongs to the base.
Practice: Easy
- Run the worked example, then add prints for
x - y,x * y, andx / y; note which new result is afloatand why. - Evaluate
7 // 2,-7 // 2,7 % 2, and-7 % 2, and check each pair against(a // b) * b + a % b == a. - Evaluate
not 0,not 1,0 or 5, and1 and 5; for each, name the value that comes back and its type.
Practice: Medium
- Rewrite
0 < y < xas two comparisons joined byand; explain which version evaluatesytwice and when that matters for a function call. - Build a truth table in a small script for
andandorwith the operand pairs(0, 1),("", "x"), and(None, 2); classify when the result is an operand rather than abool. - Write two expression pairs that differ only in parentheses (
-2 ** 2versus(-2) ** 2,2 + 3 * 4versus(2 + 3) * 4) and run both; record how precedence groups each.
Practice: Hard
- Walk the worked example line by line and write, for each line, the operator, the operand types, the operation it resolves to for built-in ints, and the resulting type.
- Use
inwith a list, a string, and a dict, and record how membership works in each; include one failing case and read the exception it raises. - Evaluate
x + y * 2 ** 2 // 3by hand first, then let Python compute it; if the results differ, point at the precedence rule you had mis-ordered.
Lesson checklist
- I can evaluate
//and%on negative operands and check them with the floor-division identity. - I can say whether a given
andororexpression returns aboolor one of its operands. - I can choose
==oriscorrectly and explain the difference with an int example. - I can group a mixed expression by precedence and add parentheses where humans need them.
Remember
Operators dispatch to operand types: arithmetic, membership, and identity all mean what the left object's class defines, within the grouping that precedence and chaining impose. Keep two habits from this lesson: read `//` and `%` through the floor identity, and reserve `is` for identity while `==` compares values.
Interview angles
What is the main purpose of **Arithmetic operators**?+
Arithmetic operators delegate to numeric or user-defined special methods. The same syntax can have different meanings for different operand types, such as + for numbers, strings, and lists.
What should you pay attention to when using **Floor division**?+
// performs floor division: the result is rounded toward negative infinity, not merely truncated toward zero. This distinction matters for negative operands.
How does **Modulo** fit into this lesson?+
% returns the remainder paired with Python's floor-division rule. For a positive divisor, the result is non-negative even when the dividend is negative.
Why does `-7 // 2` print `-4`, and what is `-7 % 2` in the same pair?+
// floors the exact result toward negative infinity, and -3.5 floors to -4. The matching remainder keeps (a // b) * b + a % b == a true, so -7 % 2 is 1, the non-negative remainder for a positive divisor.