[Python] basic grammar---3, operation symbols

1.3 Operation symbols

Arithmetic Operator

+: Addition; sequence connection

>>> 1+2
3
>>> "abc"+"abc"
'abcabc'
>>> [1,2,3]+[1,2,3]
[1, 2, 3, 1, 2, 3]

-: Subtraction

>>> 3-2
1
>>> 3.14-2.89
0.25

*: Multiplication; sequence repeat

>>> 2*3
6
>>> "abc"*3
'abcabcabc'
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

/: Division, the result is a decimal

>>> 10/3
3.3333333333333335
>>> 9/2
4.5

//: Divide, if there is a decimal, the result is a decimal (integer + decimal point)

>>> 10//3
3
>>> 9//2
4
>>> 10.0//3
3.0
>>> 9.0//2
4.0

**: Exponentiation

>>> 2**4
16
>>> 81**0.5
9.0

%: Take the remainder

>>> 10%3
1
>>> 10%-3     #(10%3)-3
-2
>>> -10%3     #-(10%3)+3
2
>>> -10%-3
-1
​
>>> 7 % 4
3
>>> 7 % -4  # 3 -> 3 + -4 -> -1
-1
>>> -7 % 4  # 3 -> -3 + 4 -> 1
1
>>> -7 % -4
-3

Assignment operator

Mainly for variables

+=,-=,*=,/=,//=,**=,%=Attributed to?=

     a ?= 1
     a = a ? 1

>>> a = 1
>>> a += 1
>>> a
2
>>> a -= 1
>>> a
1
>>> a *= 10
>>> a
10
>>> a /= 2
>>> a
5.0
>>> 10 /= 2
  File "<stdin>", line 1
SyntaxError: cannot assign to literal
>>> a = 1
>>> b = 2
>>> a += b
>>> a
3
# 左边必须是变量 右边变量或者常量都行

Comparison operator

The result of the operation can only be of Boolean type

>大于,<小于,>=大于等于,<=小于等于,==等于,!=不等于

Note: ==Always compare the value of the object data

>>> 3 > 2
True
>>> 1 < 2
True
>>> 1 != 2
True
>>> 2 == 2
True

The above code is called布尔表达式

Logical Operators

The result of the operation can only be Boolean

and逻辑与,or逻辑或,not 逻辑非

And and or binocular operators, not unary operators, the participating data must be of Boolean type

>>> 3 and 2
2
>>> 3 > 2 and 2 > 1
True
>>> 3 > 2 or 1 > 2
True
>>> not 3 > 2
False
>>> not False
True
>>> not True
False

Shift operator

&位与,|位或<<左移>>右移^异或

>>> 12 & 7
4
"""
1100
0111 &
0100
"""
>>> 12 | 7
15
"""
1100
0111 |
1111
"""
>>> 2 << 4
32
"""
    0010
00100000
2 * 2^4
"""
>>> 3 << 3
24 # 3 * 2^3
>>> 16 >> 2
4
"""
10000
00100
16 / 2^2
"""
>>> 10 ^ 7
13
"""
1010
0111 ^
1101
"""

Guess you like

Origin blog.csdn.net/trichloromethane/article/details/108267279