Skip to content

Operators

a, b = 10, 3
print(a + b) # 13 — addition
print(a - b) # 7 — subtraction
print(a * b) # 30 — multiplication
print(a / b) # 3.333... — true division (always float)
print(a // b) # 3 — floor division
print(a % b) # 1 — modulo
print(a ** b) # 1000 — exponentiation
print(5 == 5) # True
print(5 != 3) # True
print(5 > 3) # True
print(5 < 3) # False
print(5 >= 5) # True
print(5 <= 4) # False
print(True and False) # False
print(True or False) # True
print(not True) # False
# Short-circuit evaluation
x = None
y = x or "default" # "default"
z = x and x.upper() # None (short-circuits)
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x /= 4 # x = 6.0
x //= 2 # x = 3.0
x **= 3 # x = 27.0
x %= 5 # x = 2.0

Assigns and returns a value in a single expression:

# Without walrus
data = get_data()
if data:
process(data)
# With walrus
if data := get_data():
process(data)
# Useful in while loops
while chunk := file.read(1024):
process(chunk)
a, b = 0b1010, 0b1100 # 10, 12
print(a & b) # 8 — AND
print(a | b) # 14 — OR
print(a ^ b) # 6 — XOR
print(~a) # -11 — NOT
print(a << 1) # 20 — left shift
print(a >> 1) # 5 — right shift
a = [1, 2]
b = a
c = [1, 2]
print(a is b) # True — same object
print(a is c) # False — equal but different objects
print(a is not c) # True
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
# Works on strings, dicts (checks keys), sets
print("a" in "banana") # True
print("key" in {"key": 1}) # True
PrecedenceOperators
Highest**
+x, -x, ~x (unary)
*, /, //, %
+, -
<<, >>
&
^
|
==, !=, <, >, <=, >=, is, in
not
and
Lowestor