int
float
fractions.Fraction
decimal.Decimal
int(f):舍去小數部分,只保留整數部分,所以int(-3.8)的結果為-3
math.trunc(f):同int(f)
round(f, digits):四舍五入保留digits位小數。
math.floor(f)
math.ceil(f)
math.isinf()
math.isfinite()
math.isnan()
float.is_integer()
以下3中方法都表示開平方
math.sqrt(144)
144**0.5
pow(144,0.5)
int(s,base):第一個參數為一個表示數字的字符串,第二個參數為進制。int('111',2)表示把二進制字符串'111'轉換為整數。
oct, hex, bin:表示把一個數字轉為相應的進制的字符串表示形式,所以結果都是str而不是數字。
0xfe、0b11111110、0o376和254在Python的內部都是一樣的,表示數字254,這幾種表示方式對Python而言沒有任何差別。而'0xfe'則僅僅是一個字符串,如果需要轉為整數需要借助int函數,int('0xfe',16)。
用來做一些數學運算
用來生成一些隨機數。
該模塊提供了很多的function,特別有用。
random.random():產生[0,1)之間的隨機數
random.randint(min, max):產生[min, max)之間的隨機整數
random.choice(iterable):從可迭代對象中隨機選取一個元素返回。
random.sample(iterable, k):從iterable中隨機選取不重復的k個元素,以數組的形式進行返回。
random.randrange(start, stop, step):在[start, stop)中以步長step進行步進,隨機產生一個元素。
random.shuffle(l):對序列進行原地隨機打亂順序,返回None。一定要注意這是原地起作用的。
如果需要結果是精準的,那么可以使用該模塊。
decimal.Decimal(str):用來創建一個Decimal對象。
decimal.getcontext().PRec=n:設置小數點的位數。
如果需要結果是精準的,那么可以使用該模塊。
x=fractions.Fraction(1,3)
y=fractions.Fraction(0.25)
z=fractions.Fraction(*(3.25.as_integer_ratio()))
新聞熱點
疑難解答