import random
print(random.random()) # 默認限制在0-1的小數
print(random.randint(1, 8)) # 1-8的整數 包含1和8
print(random.choice('joe smith')) # 隨機選擇一個字符
print(random.choice(['joe', 'smith'])) # 元組中隨機選擇
print(random.randrange(1, 3)) # 1-3的整數,不包含3
print(random.sample([1, '2', [3]], 2)) # 列表[1, '2', [3]]三個元素,隨機兩個組合
print(random.uniform(2, 3)) # 大於2,小於3的小數
lst1 = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(lst1)
print(lst1) # 打亂順序 相當於洗牌
要點:
- random() 生成0-1之間的小數
- randint(1,9) 生成1-9之間的整數,包含1,9
- choice(‘abc’) 隨機選擇一個字符
- choice(['a', 'b']) 隨機選擇一個元素
- randrange (1,3) 生成1-3之間的整數,不包含3
- sample([a,b,c],2) 隨機選擇列表內的兩個元素組合
- uniform(2,3) 生成2-3之間的小數
- shuffle(list): list=[1,2,3,4,5] 。相當於重新洗牌,隨機化
import string
# 生成5位驗證碼 數字+字母
def v_code():
code = ''
for i in range(5):
# 方式一
c = random.randint(65, 90) # 隨機生成字母
add_letter = chr(c)
# 方式二
s = string.ascii_letters # 隨機生成字母
add_letter = random.choice(s)
add_num = random.randrange(10)
if i == 2 or i == 4:
add = add_letter
else:
add = add_num
print(code + str(add), end='')
v_code()
要點:
- 隨機生成字母:方式一:關鍵是 chr() 。
- 隨機生成字母:方式二:關鍵是string.ascii_letters , choice()