python的內建模組random隨機模組方法詳解以及使用案例(五位元隨機驗證碼的實現)

來源:互聯網
上載者:User

標籤:集合   depend   nts   number   返回   TE   integer   point   form   

1、random(self):

Get the next random number in the range [0.0, 1.0)

取0到1直接的隨機浮點數

import randomprint(random.random())C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py0.3105503800442595
2、randint(self, a, b)

Return random integer in range [a, b], including both end points.

返回a,b之間的隨機整數,包括a和b

import randomprint(random.randint(5,99))C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py53
3、randrange(self, start, stop=None, step=1, _int=int):

Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want

返回a,b直接的隨機整數,不包括b,就是>=a 小於b的範圍

import randomprint(random.randrange(1,9))C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py3

還可以指定步長

import randomprint(random.randrange(1,9,step=2))C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py5
4、choice(self, seq)

Choose a random element from a non-empty sequence   [?el?m?nt] 元素  sequence 序列

取一個不是空的序列裡面的隨機的一個元素

import randomprint(random.choice([11,22,33]))C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py22
5、sample(self, population, k)

Chooses k unique random elements from a population sequence or set

選擇k個隨機元素從序列裡面或者是集合裡面,給返回的是一個列表

下面這個例子就是從集合裡面隨機取2個元素

import randomprint(random.sample({11,22,"gouguoqi",66},2))C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py[‘gouguoqi‘, 11]
6、uniform(self, a, b): 

Get a random number in the range [a, b) or [a, b] depending on rounding

選擇a,b之間的隨機數的浮點數

import randomprint(random.uniform(2,900))C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py621.520221600369
7、shuffle(self, x, random=None)
就是對列表中的元素進行重新洗牌(打亂順序,沒什麼卵用)
import randomret=[11,22,33,44,55]random.shuffle(ret)print(ret)C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py[33, 22, 55, 44, 11]

8、製作五位元隨機驗證碼

import randomdef v_code():    ret=""    for n in range(5):#迴圈幾次        num=random.randint(0,9)#取0-9之間的隨機數字        alf=chr(random.randint(65,122))#65到122之間的chr就是小寫a到z和大寫A到Z的範圍        s=str(random.choice([num,alf]))#用choice的方法隨機從列表裡面取一個元素,轉換成str        ret+=s#每次迴圈給ret加個s,s是字串,所以最後ret就是5位元字和字母組合的驗證碼    return retprint(v_code())C:\python35\python3.exe D:/pyproject/day21模組/random隨機模組.py6s070

python的內建模組random隨機模組方法詳解以及使用案例(五位元隨機驗證碼的實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.