iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Operators

Python's operators cover arithmetic, comparison, logical, assignment, identity, membership, and bitwise. Most do what you'd expect; the surprises are listed below.

Arithmetic

+ - * /, then // (floor div), % (modulo), ** (power).

Comparison

== != < > <= >=. They chain: 0 < x < 10.

Logical

and or not. They short-circuit and return the value that decided the answer, not a boolean.

Assignment

= += -= *= /= //= %= **= |= &= ^=. Plus the walrus := introduced in 3.8 for inline assignment in expressions.

PYTHON
while (line := input('> ')) != 'quit':
    print('got:', line)

Identity

OpMeans
x is ySame object in memory.
x == ySame value (uses __eq__).

Membership

PYTHON
'a' in 'banana'      # True
3   in [1, 2, 3]      # True
'x' not in {'a','b'}  # True

Bitwise

& | ^ ~ << >> — and the same operators on sets do union/intersection/etc.

Tip: Precedence beans: not binds tighter than and which binds tighter than or. When mixing, parens make it clear and stop tomorrow-you from second-guessing.

Example

Example
# Arithmetic, comparison, logical, identity, membership
print(2 + 3, 2 ** 10)
print(2 < 3 and 3 < 4)
print(2 in [1, 2, 3])
a = b = []
print(a is b)  # True — same object
Try it Yourself »

Exercise

Identity comparison operator.

if x None:

Test yourself

Q1. Power operator is…
Q2. The walrus operator is…
Q3. a is b tests…

Discussion

Loading…