Basics
Operators
Operators are the punctuation and keywords that combine values into expressions. Some operators compute new values, some compare values, and some ask relationship questions such as membership or identity.
This page is the surface map. Focused examples explain the deeper behavior of numbers, booleans, conditions, sets, assignment expressions, and operator overloading.
Read operators by the question they ask: arithmetic computes, comparison answers true or false, boolean operators combine truth values, membership searches a container, and specialized operators should only appear when the data shape calls for them.
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 walrus operator := assigns inside an expression: the parenthesized part both names the length and passes it on to the comparison. Assignment expressions shows where that earns its place.
Source
items = ["a", "b"]
print((size := len(items)) > 0)
print(size)Output
True
2and and or short-circuit: the right side runs only when the left side cannot already determine the result. Here 10 / count would fail with a division-by-zero error if it ran, but the left side settles both answers first. The result is the last operand evaluated, so count == 0 and "empty" produces "empty".
Source
count = 0
print(count != 0 and 10 / count)
print(count == 0 or 10 / count)
print(count == 0 and "empty")Output
False
True
emptyNotes
- 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.
@is the matrix-multiplication operator. No built-in type implements it; operator overloading shows how a class gives@,+, or==its own meaning.
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
True
2
False
True
empty
Execution time appears here after you run the example.