按算术运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、运算符优先级以及相关库进行整理:
1. 算术运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
a = 10 b = 3 # 加法 print(a + b) # 13 # 减法 print(a - b) # 7 # 乘法 print(a * b) # 30 # 除法 print(a / b) # 3.3333333333333335 # 地板除法 print(a // b) # 3 # 取余数 print(a % b) # 1 # 幂运算 print(a ** b) # 1000 |
2. 比较运算
1 2 3 4 5 6 7 8 9 |
a = 10 b = 3 print(a == b) # False print(a != b) # True print(a > b) # True print(a < b) # False print(a >= b) # True print(a <= b) # False |
3. 逻辑运算
1 2 3 4 5 6 |
a = True b = False print(a and b) # False print(a or b) # True print(not a) # False |
4. 赋值运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
a = 10 a += 5 # 相当于 a = a + 5 print(a) # 15 a -= 3 # 相当于 a = a - 3 print(a) # 12 a *= 2 # 相当于 a = a * 2 print(a) # 24 a /= 4 # 相当于 a = a / 4 print(a) # 6.0 a //= 2 # 相当于 a = a // 2 print(a) # 3 a %= 2 # 相当于 a = a % 2 print(a) # 1 a **= 3 # 相当于 a = a ** 3 print(a) # 1 |
5. 成员运算
1 2 3 4 5 6 |
a = [1, 2, 3, 4, 5] print(3 in a) # True print(6 in a) # False print(3 not in a) # False print(6 not in a) # True |
6. 身份运算
1 2 3 4 5 6 7 8 |
a = [1, 2, 3] b = [1, 2, 3] c = a print(a is b) # False, 因为 a 和 b 引用不同的对象 print(a is c) # True, 因为 c 是 a 的引用 print(a is not b) # True print(a is not c) # False |
7. 运算符优先级
优先级从高到低:
**
(指数)+x
,-x
,~x
(正负号,按位取反)*
,/
,//
,%
(乘,除,地板除,取余)+
,-
(加,减)<<
,>>
(左移,右移)&
(按位与)^
(按位异或)|
(按位或)==
,!=
,>
,<
,>=
,<=
(比较)is
,is not
,in
,not in
(身份,成员)not
(逻辑非)and
(逻辑与)or
(逻辑或)=
(赋值)
8. 相关库
Python 提供了许多内置库和模块来处理更复杂的运算:
math
:基本数学函数cmath
:复数数学函数decimal
:十进制浮点运算fractions
:有理数运算random
:生成随机数statistics
:基本统计函数
使用示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import math import random import statistics # math 模块示例 print(math.sqrt(16)) # 4.0 print(math.sin(math.pi / 2)) # 1.0 # random 模块示例 print(random.randint(1, 10)) # 生成 1 到 10 之间的随机整数 # statistics 模块示例 data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(statistics.mean(data)) # 5.5 print(statistics.median(data)) # 5.5 print(statistics.stdev(data)) # 3.0276503540974917 |