day32-常見內建模組
阿新 • • 發佈:2018-11-29
一、random模組
#隨機小數
>>> random.random() # 大於0且小於1之間的小數0.7664338663654585
>>> random.uniform(1,3) #大於1小於3的小數1.6270147180533838
#隨機整數
>>> random.randint(1,5) # 大於等於1且小於等於5之間的整數
>>> random.randrange(1,10,2) # 大於等於1且小於10之間的奇數
#隨機選擇一個返回
>>> random.choice([1,'23',[4,5]]) # 1或者23或者[4,5]
#隨機選擇多個返回,返回的個數為函式的第二個引數
>>> random.sample([1,'23',[4,5]],2) #列表元素任意2個組合[[4, 5], '23']
#打亂列表順序
>>> item=[1,3,5,7,9]
>>> random.shuffle(item) # 打亂次序
>>> item
[5, 1, 3, 7, 9]
練習:生成隨機驗證碼
生成5位驗證碼,包括數字和大小寫字母
import random code = '' for i in range(n): rand_num = str(random.randrange(0, 10)) rand_str1= chr(random.randint(97, 122)) rand_str2 = chr(random.randint(65, 90)) code += random.choice([rand_num, rand_str1, rand_str2]) print(code(5)) #結果:0zwUR