1. 程式人生 > 其它 >16.3 random 隨機模組

16.3 random 隨機模組

# 隨機模組
import random

# print(random.randint(1,6)) # 1 # 隨機取一個你提供的整數範圍內的數字 包含首尾

# print(random.random()) # 0.2636316825914742 # # 隨機取0-1之間小數

# print(random.choice([1,2,3,4,5,6])) # 搖號 隨機從列表中取一個元素

# res = [1,2,3,4,5,6]
# random.shuffle(res) # 洗牌
# print(random.choice([1,2,3,4,5,6]))# 搖號 隨機從列表中取一個元素

# res = [1,2,3,4,5,6]
# random.shuffle(res) # 洗牌
# print(res)

# 生成隨機驗證碼
"""
大寫字母 小寫字母 數字

5位數的隨機驗證碼
chr
random.choice
封裝成一個函式,使用者想生成幾位就生成幾位
"""

def get_code(n):
code = ''
for i in range(n):
# # 先生成隨機的大寫字母 小寫字母 數字
upper_str = chr(random.randint(65,90))
lower_str = chr(random.randint(97,122))
random_int = str(random.randint(0,9))
# 從上面三個鍾隨機選擇一個作為隨機驗證碼的某一位
code += random.choice([upper_str,lower_str,random_int])
return code
res = get_code(4) # OYwJ
print(res)