Introduction & Syntax
Operators and Expressions · Study material
Operators are where Python quietly differs from C, C++ and Java – and where written tests set their traps. / always gives a float, // floors toward minus infinity, -2 ** 2 is -4, and and or return operands rather than True/False, comparisons can be chained, and there is no ++. This topic covers every operator family with its precedence, the conditional expression and the walrus operator, then tests you with 50 practice questions run on Python 3.
On this page
- Arithmetic: / vs //, % and ** (with negative numbers)
- Precedence and associativity
- Comparison chaining
- Logical operators and short-circuiting
- Bitwise, identity and membership operators
- Conditional expression, augmented assignment and :=
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 7 * 3 | 21 |
/ | true division – always a float | 8 / 2 | 4.0 |
// | floor division – rounds toward −∞ | -7 // 2 | -4 |
% | remainder – sign of the divisor | -7 % 2 | 1 |
** | power | 2 ** 10 | 1024 |
The rule (a // b) * b + a % b == a always holds, which is why -17 // 5 is -4 and -17 % 5 is 3. C and Java truncate toward zero instead, giving -3 and -2.
a, b = 17, 5
print(a + b, a - b, a * b) # 22 12 85
print(a / b, a // b, a % b) # true division, floor division, remainder
print(a ** 2, 2 ** 0.5) # power (a float exponent gives a float)
# // floors toward MINUS infinity, and % takes the sign of the divisor
print(-17 // 5, -17 % 5) # -4 3 because -4 * 5 + 3 == -17
print(17 // -5, 17 % -5) # -4 -3
print(divmod(17, 5), divmod(-17, 5))
22 12 85 3.4 3 2 289 1.4142135623730951 -4 3 -4 -3 (3, 2) (-4, 3)
Precedence and associativity
From highest to lowest: brackets → ** → unary +x -x ~x → * / // % → + - → shifts << >> → & → ^ → | → comparisons, in, is → not → and → or → conditional expression → :=. All binary operators are left-associative except **, which is right-associative. When in doubt, add brackets – they cost nothing and make code readable.
print(2 + 3 * 4) # * before + → 14
print((2 + 3) * 4) # brackets first → 20
print(2 ** 3 ** 2) # ** is RIGHT-associative: 2 ** 9 → 512
print(-2 ** 2) # ** binds tighter than unary minus: -(2 ** 2) → -4
print(10 - 4 - 3) # other operators are left-associative: (10 - 4) - 3 → 3
print(100 / 10 / 5) # (100 / 10) / 5 → 2.0
print(not 1 == 2) # comparisons before not: not (1 == 2) → True
14 20 512 -4 3 2.0 True
Comparison operators and chaining
== != < > <= >= return True or False. Python lets you chain them: a < b < c means a < b and b < c, with b evaluated once. Numbers of different types compare by value (5 == 5.0), strings compare by Unicode code points, and sequences compare item by item. Ordering a str against an int ("10" > 5) is a TypeError.
age = 21
print(18 <= age < 60) # chained: (18 <= age) and (age < 60)
print(1 < 3 > 2) # (1 < 3) and (3 > 2) → True
print(5 == 5.0, "5" == 5) # int and float compare by value; str never equals int
print("apple" < "banana", "Zoo" < "apple") # strings compare by Unicode code point: 'Z' (90) < 'a' (97)
print([1, 2, 3] < [1, 3]) # lists compare item by item
True True True False True True True
Logical operators: and, or, not
not always returns a bool. and and or return one of their operands: x or y gives x if x is truthy, else y; x and y gives x if x is falsy, else y. Both short-circuit – the right side is not evaluated when the left side already decides the result – which is why name or "Guest" is a common way to supply a default.
# and / or return one of their OPERANDS, not necessarily True/False
print(0 or "default") # first truthy operand, else the last
print("" and "never") # first falsy operand, else the last
print(3 and 7, None or 0)
# Short-circuit: the right side runs only if it is needed
def check(label, value):
print(" evaluating", label)
return value
print(check("A", False) and check("B", True))
print(check("C", True) or check("D", True))
default 7 0 evaluating A False evaluating C True
Bitwise operators
& (AND), | (OR), ^ (XOR), ~ (NOT, equal to -(x + 1)), << and >> (shifts) work on the binary form of integers. Note that ^ is XOR, not power.
a, b = 12, 10 # 1100 and 1010 in binary
print(a & b, a | b, a ^ b) # AND 1000, OR 1110, XOR 0110
print(~a) # NOT: -(a + 1)
print(a << 2, a >> 2) # shift: multiply / floor-divide by 4
print(f"{a:04b} {b:04b} {a ^ b:04b}")
print(13 & 1, 16 & 15 == 0) # odd test; power-of-two test
8 14 6 -13 48 3 1100 1010 0110 1 True
Identity and membership
is / is not test whether two names refer to the same object; in / not in test membership – a substring in a string, an item in a list, tuple or set, a key in a dictionary.
print("nan" in "banana", "ab" in "banana") # substring test
print(3 in [1, 2, 3], 4 not in (1, 2, 3))
print("a" in {"a": 1}, 1 in {"a": 1}) # dicts test their KEYS
x = None
nums = [1, 2]
same = nums
print(x is None, nums is same, nums is [1, 2]) # identity, not equality
True False True True True False True True False
Conditional expression, augmented assignment and the walrus operator
a if condition else b picks a value in a single expression. Augmented operators such as x *= 2 + 1 evaluate the whole right side first. Python has no ++ or --: write x += 1. The walrus operator := (Python 3.8) assigns a value and returns it inside an expression – handy in if and while conditions.
marks = 72
result = "pass" if marks >= 40 else "fail" # conditional expression
print(result)
# := assigns AND returns the value, inside an expression (Python 3.8+)
data = [4, 8, 15, 16, 23, 42]
if (n := len(data)) > 5:
print(f"{n} items is too many; using the first 5")
x = 3
x *= 2 + 1 # the WHOLE right side first: x = x * (2 + 1)
print(x)
pass 6 items is too many; using the first 5 9
Common mistakes
- Using ^ for power – it is XOR; use
**. - if x = 5: – assignment is not allowed in a condition; use
==(or:=deliberately). - if grade == "A" or "B": – always true; write
grade in ("A", "B"). - Expecting // to truncate – it floors:
-7 // 2is -4. - -2 ** 2 – is -4; write
(-2) ** 2for 4. - x++ – a SyntaxError; use
x += 1. - Integer // where an average is wanted – use
/.
Key points to remember
- / returns a float; // floors toward −∞; % takes the divisor's sign.
- ** is right-associative and binds tighter than unary minus.
- Comparisons chain: a < b < c.
- and / or return operands and short-circuit.
- in on a dict tests keys.
- is compares identity; == compares values.
- No ++ or --; := assigns inside an expression.
Frequently asked questions
Why does Python floor instead of truncate?
So that a % b always has the sign of b and (a // b) * b + a % b == a holds – useful for clock arithmetic and indexing. math.trunc() or int(a / b) give truncation if you need it.
Is there a ternary operator?
Yes: value_if_true if condition else value_if_false.
When should I use the walrus operator?
When a value is computed in a condition and used again right after, e.g. while (line := f.readline()):. Avoid it where a plain assignment reads better.
Where can I learn more?
Read Python Arithmetic Operators and Comparison and Logical Operators in the Python tutorial, then practise with the exercises below.