Basics

Operators

Operators combine, compare, and test values in expressions.

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
*+423
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 @ 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

6

The 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

2

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

Notes

See also

Run the complete example

Example code

Expected output

15
2
2
32
True
True
True
1
7
6
6
6
2

Execution time appears here after you run the example.