标签:
算数运算:
a=10 b=20 print(a+b) #相加 print(a-b) #减法 print(a*b) #乘法 print(b/a) #除法 print((b+2)%a) #求余数 print(b**a) #幂次方 print(b//a) #取整数 #------------------------------------------------结果如下: 30 -10 200 2.0 2 10240000000000 2
比较运算:
赋值运算:
逻辑运算:
成员运算:
身份运算:
位运算:
计算表示的最小的单位为一个二进制位 计算存储的最小的单位为一个二进制位(bit) 8bit = byte (字节) 1024byte = 1kbyte 取八个二进制位(bit)。 a = 60 二进制位,如下: 128 64 32 16 8 4 2 1 ------------------------------ 0 0 1 1 1 1 0 0 = 60 b = 13 二进制位,如下: 128 64 32 16 8 4 2 1 ------------------------------ 0 0 0 0 1 1 0 1 = 13 a&b 按位于(and),两个同时为真的值是为结果,结果如下: 128 64 32 16 8 4 2 1 ------------------------------- 0 0 1 1 1 1 0 0 = 60 0 0 0 0 1 1 0 1 = 13 ------------------------------- 0 0 0 0 1 1 0 0 = 12 a|b 按位或(or),两个有一个为真时,结果为真,如下: 128 64 32 16 8 4 2 1 ------------------------------- 0 0 1 1 1 1 0 0 = 60 0 0 0 0 1 1 0 1 = 13 ------------------------------- 0 0 1 1 1 1 0 1 = 61 a^b 按位异(^),相同为0,不同为1,如下 128 64 32 16 8 4 2 1 ------------------------------- 0 0 1 1 1 1 0 0 = 60 0 0 0 0 1 1 0 1 = 13 ------------------------------- 0 0 1 1 0 0 0 1 = 49 ~a 按位取反(~),所得结果减256,视为结果。 128 64 32 16 8 4 2 1 ------------------------------- 0 0 1 1 1 1 0 0 = 60 0 0 0 0 1 1 0 1 = 13 ------------------------------- 1 1 0 0 0 0 1 1 =195 195 -256 = -61(结果) a<< 左移动运算符,a<<2 移动两个位。如下: 128 64 32 16 8 4 2 1 ------------------------------- 0 0 1 1 1 1 0 0 = 60 ------------------------------- 1 1 1 1 0 0 0 0 = 240 <--移动两个位,后面不足补0. a>> 右移动运算符,a>>2 移动两个位。如下: 128 64 32 16 8 4 2 1 ------------------------------- 0 0 1 1 1 1 0 0 = 60 ------------------------------- 0 0 0 0 1 1 1 1 = 15 -->,右移两位,空出部分补0
a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b; # 12 = 0000 1100 print("Line 1 - Value of c is ", c) c = a | b; # 61 = 0011 1101 print("Line 2 - Value of c is ", c) c = a ^ b; # 49 = 0011 0001 print("Line 3 - Value of c is ", c) c = ~a; # -61 = 1100 0011 print("Line 4 - Value of c is ", c) c = a << 2; # 240 = 1111 0000 print("Line 5 - Value of c is ", c) c = a >> 2; # 15 = 0000 1111 print("Line 6 - Value of c is ", c)
结果:
Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15 进程已结束,退出代码0
运算符优先级:
更多内容可以访问:
http://www.runoob.com/python/python-operators.html
标签:
原文地址:http://www.cnblogs.com/WDeLong/p/5853536.html