1. 程式人生 > 其它 >計算機二級python自主複習其二——數字

計算機二級python自主複習其二——數字

前言

承接上文,複習完字串,根據考綱,基本資料型別中還有數字尚未複習,那麼今天火速複習一下!

數字

眾所周知,數字分為整型(int)、浮點型(float)、複數(complex),數字的運算除了加減乘除之外,還有取餘、取整等運算。

本次複習我們跳過以上,重點複習一下有關數字的函式。

數字型別轉換

int(x [,base ])         x轉換為一個整數  
long(x [,base ])        x轉換為一個長整數  
float(x )               x轉換到一個浮點數  
complex(real [,imag ])  建立一個複數  
str(x )                 將物件 x 轉換為字串  
repr(x )                將物件 x 轉換為表示式字串  
eval(str )              用來計算在字串中的有效Python表示式,並返回一個物件  
tuple(s )               將序列 s 轉換為一個元組  
list(s )                將序列 s 轉換為一個列表  
chr(x )                 將一個整數轉換為一個字元  
unichr(x )              將一個整數轉換為Unicode字元  
ord(x )                 將一個字元轉換為它的整數值  
hex(x )                 將一個整數轉換為一個十六進位制字串  
oct(x )                 將一個整數轉換為一個八進位制字串
......

數字函式

abs(x)                  返回x的絕對值  
ceil(x)                 返回x的上入整數  
exp(x)                  返回e的x次冪  
floor(x)                返回x的下舍整數  
max(x1,x2,...)          返回最大值  
min(x1,x2,...)          返回最小值  
pow(x,y)                x的y次方,相當於x**y  
......

隨機數函式

有關隨機數的函式,基本上要用到random庫,而random庫也是計算機二級必考點。

dir(random)

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 
'_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos
', '_e',
'_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test',
'_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate',
'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random',
'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

主要講一講常用的choice(),choices(),randint(),random(),randrange(),shuffle(),uniform()

import random
random.choice([1,2,3,4,5])          #從序列中隨機抽取一個元素
random.choices([1,2,3,4,5], k=5)    #從序列中隨機選取k次元素,組成列表,可分配權重
random.randint(0,9)                 #從範圍內隨機選一個整數
random.random()                     #從0,1間隨機選一個浮點數,不接受引數
random.randrange(0,100,2)           #從範圍內按指定數字遞增的順序隨機一個數
random.shuffle(list)                #將序列隨機排序
random.uniform(0,9)                #從範圍內隨機選一個浮點數

(詳情參見https://www.runoob.com/python/python-numbers.html)