python之random函數

來源:互聯網
上載者:User

標籤:utf-8   排序   隨機排序   string   list   .com   post   lis   www.   

 1 #-*- coding:utf-8 -*- 2  3 # random各種使用方法 4 import random 5   6 # 隨機產生[0.1)的浮點數 7 print("random():", random.random()) 8   9 # 隨機產生1000-9999之間的整數10 print("randint(1000, 9999):", random.randint(1000, 9999))11  12 # 隨機產生0-20之間的偶數13 print("randrange(0, 21, 2):", random.randrange(0, 21, 2))14  15 # 隨機產生0-20之間的浮點數16 print("uniform(0, 20):", random.uniform(0, 20))17  18 # 從序列中隨機播放一個元素19 list_string = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]20 print("choice(list):", random.choice(list_string))21 print("choice(string):", random.choice(‘abcd‘))22  23 # 對列表元素隨機排序24 list_number = [1, 2, 3, 4, 5]25 random.shuffle(list_number)26 print("shuffle(list):", list_number)27  28 # 從指定序列中隨機擷取指定長度的片斷29 print("sample(sequence):", random.sample(‘abcdefg‘, 2))
 

結果:

random(): 0.39840036736565154randint(1000, 9999): 5736randrange(0, 21, 2): 2uniform(0, 20): 15.785447740011865choice(list): bchoice(string): bshuffle(list): [5, 3, 4, 1, 2]sample(sequence): [‘f‘, ‘b‘]

編寫一個產生驗證碼:

 1 import random 2 def v_code(): 3     code=‘‘ 4     for i in range(5): 5         code+=str(random.choice([random.randrange(10),chr(random.randrange(65,91))])) 6         7     print(code) 8       9      10 v_code()

結果:

04TT3

 

 

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.