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