Basics
Operators
Arithmetic operators compute new values. Use // for floor division, % for remainder, and ** for powers.
Source
count = 10
print(count + 5)
print(count // 4)
print(count % 4)
print(2 ** 5)Output
15
2
2
32Comparison operators produce booleans. Python comparisons can chain, which keeps range checks readable.
Source
score = 91
print(80 <= score < 100)
print(score == 100 or score >= 90)
print("py" in "python")Output
True
True
TrueBitwise operators work on integer bit patterns. They are useful for masks and flags, not ordinary boolean logic. & is bitwise AND, | is bitwise OR, ^ is exclusive OR, and << shifts left.
Source
flags = 0b0011
print(flags & 0b0101)
print(flags | 0b0100)
print(flags ^ 0b0101)
print(flags << 1)Output
1
7
6
6The @ operator is reserved for matrix-like multiplication and custom types that define __matmul__.
Source
class Scale:
def __init__(self, value):
self.value = value
def __matmul__(self, other):
return self.value * other.value
print(Scale(2) @ Scale(3))Output
6The walrus operator := assigns inside an expression. Use it when naming a value avoids repeating work in a condition.
Source
items = ["a", "b"]
if (size := len(items)) > 0:
print(size)Output
2and and or short-circuit: the right side runs only when the left side cannot already determine the result. That makes them safe for guard expressions like obj and obj.value where the right side would fail on None.
Source
def loud():
print("ran")
return True
print(False and loud())
print(True or loud())
print(True and loud())Output
False
True
ran
TrueNotes
- Use the clearest operator for the question: arithmetic, comparison, boolean logic, membership, identity, or bitwise manipulation.
andandorshort-circuit, so the right side may not run.- Operators have precedence; use parentheses when grouping would otherwise be hard to read.
- Custom operator behavior should make an object feel more natural, not more clever.
See also
- related syntax: Numbers
- next depth: Equality and Identity
- specialized expression: Assignment Expressions
- next depth: Operator Overloading
Run the complete example
Expected output
15
2
2
32
True
True
True
1
7
6
6
6
2
Execution time appears here after you run the example.