Python 入门(一)

2020-12-02  本文已影响0人  浪花三朵

二进制

bin(4)
0b100
a = 1021
print(a.bit_lenght())
image.png

浮点数

  1. 用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现。
improt decimal
from decimal import Decimal
a = decimal.getcontext()  # 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。
print(a)
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)  # 结果保留了28位
print(b)
image.png
调整精度
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)
image.png

变量的比较

注意:is, is not 对比的是两个变量的内存地址;==, != 对比的是两个变量的值

比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。

a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False
True True
False False
a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False
False True
True False

enumerate() 函数

enumerate(sequence, [start=0])
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = enumerate(seasons)
print(lst)
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

异常处理

上一篇 下一篇

猜你喜欢

热点阅读