Python: Operators
Arithmetic Operators
Addition operator is +
print(3 + 4) # 7
Substract operator is -
print(3 - 4) # -1 print(3 + - 4) # -1
Multiplication operator is *
print(3 * 4) # 12
Power operator is **
print(2 ** 3) # 8
Divide operator is /
print(11 / 5) # 2.2
Quotient operator is //
print(11 // 5) # 2
Remainder (modulo) operator is %
print(11 % 5) # 1
Quotient and remainder function divmod
print(divmod(11, 5)) # (2, 1)
Assignment Operators
Add and assign +=
x = 0 x += 1 print(x) # 1
Substract and assign -=
x = 0 x -= 2 print(x) # -2
Multiply and assign *=
x = 2 x *= 3 print(x) # 6
Exponent and assign **=
x = 3 x **= 2 print(x) # 9
Divide and assign /=
x = 7 x /= 2 print(x) # 3.5
Modulus (remainder) and assign %=
x = 13 x %= 5 print(x) # 3
Quotient and assign //=
x = 13 x //= 5 print(x) # 2
Note: Python doesn't support C++ language's increment operator ++
,
nor the decrement operator --
.
WARNING: ++i
may not generate any error, but it doesn't do anything.
Bit Operators
0b101
mean binary number 101
the "{:2b}" means print in binary, and use 2 slots.
bitwise And &
print( "{:2b}".format(0b11 & 0b10) ) # binary 10
bitwise Or |
print( "{:2b}".format(0b11 | 0b10) ) # binary 11
xor ^
.
Means true if both sides differ
print( "{:2b}".format(0b00 ^ 0b10) ) # binary 10
binary invert ~
print( "{:2b}".format(~ 0b1) ) # binary -10 (odd result!)
- binary right shift
>>
- binary left shift
<<