什么是运算符?
本章节主要说明Python的运算符。举个简单的例子 4 +5 = 9 。 例子中,4 和 5 被称为操作数,"+" 称为运算符。
Python语言支持以下类型的运算符:
-
算术运算符
-
比较(关系)运算符
-
赋值运算符
-
逻辑运算符
-
位运算符
-
成员运算符
-
身份运算符
-
运算符优先级
1.算术运算符
a = 10 b = 3 c = a + b #加法 d = a - b #减法 e = a * b #乘法 f = a / b #除法 g = a % b #取模 h = a ** b #幂运算 i = a // b #整除 返回商的整数部分 print(c,d,e,f,g,h,i) # 13 7 30 3.3333333333333335 1 1000
2.比较运算符
a = 10 b = 3 d = a == b e = a != b f = a > b g = a < b h = a >= b i = a <= b print(d,e,f,g,h,i) # False True True False True False
3.赋值运算符
a = 10 b = 3 c = a d = b print(c,d) # 10,3 a = 10 b = 3 a += a print(a) # 20 a = 10 b = 3 b -= a print(b) #-7 a = 10 b = 3 a *= b print(a) #30 a = 10 b = 3 b /= a print(b) #0.3 a = 10 b = 3 b %= a print(b) #3 a = 10 b = 3 b **= a print(b) #59049 a = 10 b = 3 a //= b print(b) #3
4.位运算符
a = 11 # 1011 b = 5 # 0101 c = a & b d = a | b e = a ^ b f = ~ a g = a << 1 h = b >> 1 print(c,d,e,f,g,h) # 1 15 14 -12 22 2
5.逻辑运算符
a = 20 b = 10 c = 0 k = a and b d = a and c e = c and b f = a or b g = a or c h = c or b i = not a j = not c print(k,d,e,f,g,h,i,j) #10 0 0 20 20 10 False True
6.成员运算符
a = 1 b = 20 list = [1, 2, 3, 4, 5 ] if a in list: print("a在list里") else: print("a不在list里") if b in list: print("b在list里") else: print("b不在list里")
7.身份运算符
a = 1 b = 20 if a is b: print("a和b的地址相同") else: print("a和b的地址不相同") a = 20 if a is b: print("a和b的地址相同") else: print("a和b的地址不相同")