1. 程式人生 > >Python3.5——內建模組詳解之random模組

Python3.5——內建模組詳解之random模組

1、random模組基礎的方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu

import random

print(random.random())          #隨機產生[0,1)之間的浮點值
print(random.randint(1,6))      #隨機生成指定範圍[a,b]的整數
print(random.randrange(1,3))    #隨機生成指定範圍[a,b)的整數
print(random.randrange(0,101,2))  ##隨機生成指定範圍[a,b)的指定步長的數(2--偶數)
print(random.choice("hello"))  #隨機生成指定字串中的元素
print(random.choice([1,2,3,4])) #隨機生成指定列表中的元素
print(random.choice(("abc","123","liu")))  #隨機生成指定元組中的元素
print(random.sample("hello",3))    #隨機生成指定序列中的指定個數的元素
print(random.uniform(1,10))     #隨機生成指定區間的浮點數

#洗牌
items = [1,2,3,4,5,6,7,8,9,0]
print("洗牌前:",items)
random.shuffle(items)
print("洗牌後:",items)

執行結果:

0.1894544287915626
2
1
74
l
2
liu
['l', 'h', 'o']
1.2919229440123967
洗牌前: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
洗牌後: [6, 9, 2, 7, 1, 3, 8, 5, 4, 0]

2、random模組中方法的實際應用——生成隨機驗證碼

(1)隨機生成4位純數字驗證碼

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu

import random

check_code = ''   #最終生成的驗證碼

for i in range(4):       #4位長的純數字驗證碼
    cur = random.randint(0,9)
    check_code += str(cur)
print(check_code)
#執行結果:
#0671
(2)隨機生成4位字串驗證碼(數字與字元都有)
import random

check_code = ''
for i in range(4):
    cur = random.randrange(0,4)    #隨機猜的範圍,與迴圈次數相等
    #字母
    if cur == i:
        tmp = chr(random.randint(65,90))    #隨機取一個字母
    #數字
    else:
        tmp = random.randint(0,9)
    check_code += str(tmp)
print(check_code)
#執行結果:
#39HN