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 |