Python3.5內置模塊之random模塊用法實例分析

這篇文章主要介紹了Python3.5內置模塊之random模塊用法,結合實例形式分析了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

PS:這裏再提供幾款相關工具供大家參考使用:

在線隨機數生成工具:
http://tools.jb51.net/aideddesign/rnd_num

在線隨機生成個人信息數據工具:
http://tools.jb51.net/aideddesign/rnd_userinfo

在線隨機字符/隨機密碼生成工具:
http://tools.jb51.net/aideddesign/rnd_password

在線隨機數字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu

更多關於Python相關內容感興趣的讀者可查看本站專題:《Python數學運算技巧總結》、《Python字符串操作技巧彙總》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧彙總

希望本文所述對大家Python程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章