本文共 1653 字,大约阅读时间需要 5 分钟。
– Start
整数没有精度限制,具有无穷大小。
# 十进制整数n = 255n = int(255)print(n)# 二进制以 0b 开头n = 0b11111111n = bin(255)n = int('11111111', 2)print(n)# 八进制以 0o 开头n = 0o377n = oct(255)n = int('377', 8)print(n)# 十六进制以 0x 开头, a,b,c,d,e,f 不区分大小写n = 0xFFn = hex(255)n = int('FF', 16)print(n)
浮点数精度和 C 双精度相同。
# 定义浮点数n = 3.1415n = 3.n = .1415n = 3.14e-10 # e不区分大小写n = float('3.1415')print(n)
复数由实部和虚部组成。
# 定义复数n = 3+4jn = 3.0+4.0jn = 3jn = complex(3, 4)print(n)# 访问实部和虚部print(n.real)print(n.imag)
# 算术运算x = 3y = 2r = x + y #加print(r)r = x - y #减print(r)r = x * y #乘print(r)r = x / y #除print(r)r = x // y #除:丢弃小数部分print(r)r = x ** y #幂,相当于2的3次方print(r)r = x % y #余print(r)
Python 支持下面的四舍五入函数。
math.ceil # 向上舍入math.floor # 向下舍入round # 四舍五入math.trunc # 舍去小数
我们来测试一下。
import mathdef my_print(n): print(str(n).ljust(7) + str(math.ceil(n)).ljust(7) + str(math.floor(n)).ljust(7) + str(round(n)).ljust(7) + str(math.trunc(n)).ljust(7))print('NUM CEIL FLOOR ROUND TRUNC')my_print(5.5)my_print(2.5)my_print(1.6)my_print(1.1)my_print(1)my_print(-1)my_print(-1.1)my_print(-1.6)my_print(-2.5)my_print(-5.5)
看看下面的结果吧。
NUM CEIL FLOOR ROUND TRUNC5.5 6 5 6 52.5 3 2 2 21.6 2 1 2 11.1 2 1 1 11 1 1 1 1-1 -1 -1 -1 -1-1.1 -1 -2 -1 -1-1.6 -1 -2 -2 -1-2.5 -2 -3 -2 -2-5.5 -5 -6 -6 -5
# 求绝对值r = abs(-3)print(r)# 幂,相当于2的3次方r = pow(2, 3)print(r)# 返回 a/b 和 a%br = divmod(3, 2)print(r)
– 更多参见:
– 声 明:转载请注明出处 – Last Updated on 2018-09-05 – Written by ShangBo on 2017-04-23 – End