Operators
Operators
Section titled “Operators”Arithmetic
Section titled “Arithmetic”a, b = 10, 3print(a + b) # 13 — additionprint(a - b) # 7 — subtractionprint(a * b) # 30 — multiplicationprint(a / b) # 3.333... — true division (always float)print(a // b) # 3 — floor divisionprint(a % b) # 1 — moduloprint(a ** b) # 1000 — exponentiationComparison
Section titled “Comparison”print(5 == 5) # Trueprint(5 != 3) # Trueprint(5 > 3) # Trueprint(5 < 3) # Falseprint(5 >= 5) # Trueprint(5 <= 4) # FalseLogical
Section titled “Logical”print(True and False) # Falseprint(True or False) # Trueprint(not True) # False
# Short-circuit evaluationx = Noney = x or "default" # "default"z = x and x.upper() # None (short-circuits)Assignment
Section titled “Assignment”x = 10x += 5 # x = 15x -= 3 # x = 12x *= 2 # x = 24x /= 4 # x = 6.0x //= 2 # x = 3.0x **= 3 # x = 27.0x %= 5 # x = 2.0Walrus Operator := (Python 3.8+)
Section titled “Walrus Operator := (Python 3.8+)”Assigns and returns a value in a single expression:
# Without walrusdata = get_data()if data: process(data)
# With walrusif data := get_data(): process(data)
# Useful in while loopswhile chunk := file.read(1024): process(chunk)Bitwise
Section titled “Bitwise”a, b = 0b1010, 0b1100 # 10, 12print(a & b) # 8 — ANDprint(a | b) # 14 — ORprint(a ^ b) # 6 — XORprint(~a) # -11 — NOTprint(a << 1) # 20 — left shiftprint(a >> 1) # 5 — right shiftIdentity
Section titled “Identity”a = [1, 2]b = ac = [1, 2]
print(a is b) # True — same objectprint(a is c) # False — equal but different objectsprint(a is not c) # TrueMembership
Section titled “Membership”fruits = ["apple", "banana", "cherry"]print("apple" in fruits) # Trueprint("grape" not in fruits) # True
# Works on strings, dicts (checks keys), setsprint("a" in "banana") # Trueprint("key" in {"key": 1}) # TrueOperator Precedence (high → low)
Section titled “Operator Precedence (high → low)”| Precedence | Operators |
|---|---|
| Highest | ** |
+x, -x, ~x (unary) | |
*, /, //, % | |
+, - | |
<<, >> | |
& | |
^ | |
| | |
==, !=, <, >, <=, >=, is, in | |
not | |
and | |
| Lowest | or |