跳转至

数值型

  • 没有doublechar类型。
  • 整型int:表示整数。
  • 浮点型float:表示带有小数部分的实数。
  • 复数complex:表示复数,由实部和虚部组成。
# 创建一个实部为3,虚部为4的复数
def complex_number():
    # complex(3, 4)等价于3 + 4j
    complex1 = 3 + 4j
    complex2 = complex(3, 4)
    assert complex1 == complex2

📌 需要精确计算时

# 需要精确计算的场景,使用decimal模块而不是浮点数
def decimal_calculate():
    from decimal import Decimal
    print(12.3 * 0.1)
    print(Decimal(12.3) * Decimal('0.1'))
    print(Decimal('12.3') * Decimal('0.1'))

    # 输出:
    # 1.2300000000000002
    # 1.230000000000000071054273576
    # 1.23

📌 四舍五入,保留两位小数

def round_format():
    str1 = 3.7477926
    str2 = '{:.2f}'.format(str1)
    print(str2)  # 输出3.75
    str2 = round(str1, 2)
    print(str2)  # 输出3.75

    str1 = 3.00
    print('{:.2f}'.format(str1))  # 输出3.00
    print(round(str1, 2))  # 输出3.0

📌 负数取余

# python中的%实际是取模运算符,负数运算时无法像正数一样得到取余结果
print(-9 % 5)  # 输出1
print(-9 % -5)  # 输出-4
# divmod同时返回商和余数
print(divmod(-9, 5))  # (-2, 1)
print(divmod(-9, -5))  # (1, -4)