Python 有三种不同的内置数字类型:整数(int)、浮点数(float)和复数(complex)。分数(fractions.Fraction)和十进制数(decimal.Decimal)也可以从标准库导入使用。
不带小数点的整数也是 ints,包括十六进制(hex())、八进制(oct())和二进制(bin())数字:
# Ints are whole numbers.
>>> 1234
1234
>>> type(1234)
<class 'int'>
>>> -12
-12
包含小数点的数字(无论有没有小数部分)都被视为 floats:
>>> 3.45
3.45
>>> type(3.45)
<class 'float'>
Python 完全支持这些不同数字类型之间的算术运算。当与二元算术运算符(+、-、*、/、// 和 %)一起使用时,它会把较窄的数字转换成与它对应的较宽类型,以便保持一致。
所有数字(复数除外)都支持全部算术运算,并按运算符优先级求值。复数对数学函数(+和-之外)的支持可以在 cmath 模块中找到。
加法和减法运算符的行为和普通数学一样。
如果操作数中有一个或多个是 float,其余的 int 也会被转换成 float:
>>> 5 - 3
2
# The int is widened to a float here, and a float is returned.
>>> 3 + 4.0
7.0
与加法和减法一样,乘法也会把较窄的数字转换成较宽的类型:
>>> 3 * 2
6
>>> 3 * 2.0
6.0
除法总是返回 float,即使结果是一个整数:
>>> 6/5
1.2
>>> 6/2
3.0
如果需要 int 结果,可以用向下取整除法来截断结果。
向下取整除法通过 // 运算符完成:
>>> 6//5
1
>>> 6//2
3
求模运算符(%)返回两个操作数相除的余数:
# The result of % is zero here, because dividing 8 by 2 leaves no remainder
>>> 8 % 2
0
# The result of % is 2 here, because 3 only goes into 5 once, with 2 left over
>>> 5 % 3
2
换个角度看 5 % 3:
>>> whole_part = int(5/3)
1
>>> decimal_part = 5/3 - whole_part
0.6666666666666667
>>> whole_remainder = decimal_part * 3
2.0
幂运算通过 ** 运算符完成:
>>> 2 ** 3
8
>>> 4 ** 0.5
2
使用内置函数int()和float(),可以把数字从 int 转换成 float,也可以从 float 转换成 int:
>>> int(3.45)
3
>>> float(3)
3.0
Python 提供了一个内置函数round(<number>, <decimal_places>),用于把浮点数四舍五入到指定的小数位数。
如果没有指定小数位数,数字会四舍五入到最接近的整数,并返回 int:
>>> round(3.1415926535, 2)
3.14
>>> round(3.1415926535)
3
Python 允许你用括号对表达式进行分组。 当你想覆盖默认的运算顺序时,这会很有用。
>>> 2 + 3 * 4
14
>>> (2 + 3) * 4
20
Python 遵循 PEMDAS 规则来确定运算符优先级。
这意味着()内的计算优先级最高,其次是**,然后是*、/、//、%、+和-:
>>> 2 + 3 - 4 * 4
-11
>>> (2 + 3 - 4) * 4
4
# In the following example, the `**` operator has the highest priority, then `*`, then `+`
# Meaning we first do 4 ** 4, then 3 * 256, then 2 + 768
>>> 2 + 3 * 4 ** 4
770
Python 中的整数具有任意精度,位数只受宿主系统可用内存的限制。
浮点数通常用 C 语言的double实现(精度为 15 位小数),但具体的表示会因宿主系统而异。
复数有一个real部分和一个imaginary部分,两者都用浮点数表示。
想更详细地了解各编程语言中浮点运算的问题和局限,可以看看 0.30000000000000004.com 和 The Python Tutorial。