Basics

Operators

Operators combine, compare, and test values in expressions.

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
32
An expression like (2 + 3) * 4 parses as a tree; operator precedence and parentheses determine its shape.

Comparison 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
True

Bitwise 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
6

The 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
2

and 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
empty

Notes

See also

Run the complete example

Example code

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.