Arithmetic operators:
add | reduce | take | remove | Rounding | Take remainder | Exponentiation |
+ | - | * | / | // | % | ** |
# 加:
print(1 + 2) # 3
# 减:
print(4 - 3) # 1
# 乘:
print(2 * 5) # 10
# 除:
print(6 / 5) # 1.2
# 整除:
print(6 // 5) # 1
# 取余:
print(6 % 5) # 1
# 幂运算:
print(2 ** 3) # 8
Notice:
Integer division operation, the result of integer division is rounded down;
Remainder operation, remainder = dividend - divisor * quotient.
print(5 // -2) # -3 结果=-2.5,向下取整=-3
print(5 % -2) # -1 结果=5 - (-2) * (-3)
Assignment operator:
equal | Wait... |
= | += ··· |
a = 10
b = c = d = 10
b, c, d, = 10, 20, 30
e = 5 + 5
e += 5 # +=、-=、*=、/=、//=、%=、**=
Extension: Quickly swap the values of two variables
a, b = 10, 20
print(a, b) # 10 20
a, b = b, a
print(a, b) # 20 10
Comparison operators:
value comparison operator | equal | not equal to | more than the | greater or equal to | less than | less than or equal to |
== | != | > | >= | < | <= |
id comparison operator/identity operator Whether referencing the same object |
IDs are equal | ids are not equal |
is | is not |
a, b = 10, 10
print(id(a), id(b)) # 4336288272 4336288272
print(a == b) # True
print(a is b) # True
print(a is not b) # False
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
print(id(lst1), id(lst2)) # 4425922752 4425946240
print(lst1 == lst2) # True
print(lst1 is lst2) # False
print(lst1 is not lst2) # True
Boolean operators:
And (with) | or | No |
and | or | not |
Both values are True Returns True, otherwise False |
One of the two values is True Returns True, otherwise False |
Negate the result |
member operator Is it in the specified sequence? |
in sequence | not in sequence |
in | not in |
print('h' in 'hello') # True
print('a' not in 'hello') # True
lst = [1, 2, 3]
print(1 in lst) # True
print(1 not in lst) # False
Bit operators:
Convert a number to binary form, counting binary digits:
Bit AND | bit or | Bit XOR | bit negation | Bit shift left | Bit shift right |
& | | | ^ | ~ | << | >> |
Both corresponding bits are 1, Return 1, Otherwise 0 |
The two corresponding bits have a 1, Return 1, Otherwise 0 |
The two corresponding bits are not the same, Return 1, Otherwise 0 |
Bitwise negation, | Shift binary bits left by specified number of digits | Shift a binary bit to the right by the specified number of digits |
Operator precedence:
Arithmetic operators > Bitwise operators > Comparison operators > Boolean operators > Assignment operators