1. 数字类型
-
整数:Python 的整数长度不受限制,有无限大的精度。
-
浮点数
print(0.1 + 0.2) # 0.30000000000000004
i = 0
while i < 1:
i += 0.1
print(i)
'''
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
'''
Python的浮点数具有误差的原因,是因为Python采用IEEE754标准来存放浮点数,会产生一定精度上的误差。
但是由于误差的存在,也会带来很多问题:
print(0.3 == 0.1 + 0.2) # False
为了解决浮点数精度不够的问题,可以引入decimal模块:
import decimal as dec
a = dec.Decimal("0.1")
b = dec.Decimal("0.2")
print(a + b) # 0.3
c = dec.Decimal("0.3")
print(a + b == c) # True
科学计数法
print(0.00005) # 5e-05
print(0.0000018) # 1.8e-06
- 复数
x = 8 + 10j
print(x.real) # 获得实部 8.0
print(x.imag) # 获得虚部 10.0
- 数字之间的运算
| 操作 | 结果 |
|---|---|
| x + y | 求和 |
| x - y | 求差 |
| x * y | 求积 |
| x / y | 求商 |
| x // y | 求地板商 |
| x % y | 求余数 |
| - x | x的相反数 |
| + x | x本身 |
| abs(x) | 求x 的绝对值 |
| int(x) | 将x强制转换为整数 |
| float(x) | 将x强制转换为浮点数 |
| complex(real, imag) | 返回一个复数,real是实部,imag是虚部 |
| divmod(x, y) | 求(x // y,x % y) |
| pow(x, y) | 求x 的y 次方 |
| x ** y | 求x 的y 次方 |
print(3 / 2) # 1.5
print(3 // 2) # 1
print(-3 // 2) # -2
print(3 % 2) # 1
print(abs(-5)) # 5
print(int(1.25)) # 1
print(float(1)) # 1.0
print(complex(1, 2)) # 1 + 2i
print(divmod(6, 5)) # 1 1
print(2, 3) # 8
print(2 ** 3) # 8
2. 布尔类型
import decimal
from mpmath import fraction
# 以下情况布尔值均为False
# 定义为False的对象
print(bool(None))
print(bool(False))
# 值为0的数字类型
print(bool(0))
print(bool(0.0))
print(bool(0j))
print(bool(Decimal(0)))
print(bool(Fraction(0, 1)))
# 空的序列和集合
print(bool(''))
print(bool(()))
print(bool([]))
print(bool({}))
print(bool(set()))
print(bool(range()))
布尔类型就是特殊的整数类型
print(True == 1) # True
print(False ==0) # False
print(True + False)
print(True - False)
print(True * False)
print(False / True)
'''
1
1
0
0.0
'''
- 逻辑运算符 and,or,not
print(True and False) # False
print(True or False) # True
print(not True) # False
print(not False) # True
Python中的任何对象都能直接进行真值测试,用于if或着while语句的条件判断,也可以作为布尔逻辑运算符的操作数。
短路逻辑的核心思想:从左往右,只有当第一个操作数的值无法确定逻辑运算的结果时,才对第二个操作数进行求值。
print((not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)) # 4
print(not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9) # 4
- 运算符优先级
| 优先级 | 运算符 | 描述 |
|---|---|---|
| 1 | lambda | Lambda表达式 |
| 2 | if - else | 条件表达式 |
| 3 | or | 布尔 或 |
| 4 | and | 布尔 与 |
| 5 | not | 布尔 非 |
| 6 | in, not in, is, is not, <, <=, >, >=, !=, == | 成员测试,同一性测试,比较 |
| 7 | | | 按位 或 |
| 8 | ^ | 按位 异或 |
| 9 | & | 按位 与 |
| 10 | <<, >> | 移位 |
| 11 | +, - | 加法,减法 |
| 12 | *, @, /, //, % | 乘法,矩阵乘法,除法,地板除,取余数 |
| 13 | +x, -x, ~x | 正号,负号,按位翻转 |
| 14 | ** | 指数 |
| 15 | await x | Await表达式 |
| 16 | x[index], x[index index], x[arguments…], x.attribute | 下标,切片,函数调用,属性引用 |
| 17 | (expressions…), [expressions…], {key:value…}, {expression…} | 绑定或元组显示,列表显示,字典显示,集合显示 |
欢迎私信交流(师从小甲鱼)
8171

被折叠的 条评论
为什么被折叠?



