random模塊
導入模塊
import random
random.randrange()
返回[1,100)範圍內的隨機數整數,不包括100
>>> random.randrange(1,100)
68
>>> random.randrange(1,100,3)
16
注意:第三個參數爲步長,步長爲三時,只能返回該範圍內特定的數
比如該例子中[1,4,7,…,97]
random.randrange()
返回[1,100]範圍內的隨機數整數,包括100,第三個參數同random.randrange()用法一樣
>>> random.randint(1,100)
17
random.random()
返回[0, 1)範圍內隨機浮點數,不包括1
>>> random.random()
0.41385723239524297
random.choice()
在給定容器中隨機選擇一個元素
>>> random.choice("abcde")
'e'
>>> random.choice([1,2,3])
3
>>> random.choice({1:"a",2:"b"})
'a'
random.sample()
在給定容器中選擇特定元素
>>> random.sample("abcde",2)
['e', 'b']
random.shuffle()
隨機打亂傳入的容器(容器必須是可變對象)
>>> l = [1,2,3,4]
>>> random.shuffle(l)
>>> l
[1, 3, 2, 4]
相應案例
製作圖片驗證碼
前提知識:
string模塊內置常量
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' 小寫字母
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 大寫字母
ascii_letters = ascii_lowercase + ascii_uppercase 大寫字母+小寫字母
digits = '0123456789' 數字
hexdigits = digits + 'abcdef' + 'ABCDEF' 十六進制數
octdigits = '01234567' 十進制數
printable = digits + ascii_letters + punctuation + whitespace 可打印數
具體代碼:
使用pillow模塊製作驗證碼圖片