1. 程式人生 > >python:random模塊

python:random模塊

元素 post for 轉化 asc sam ascii碼 amp 隨機生成

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

__author__ = "Samson"

import random,string

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)

#實際應用,驗證碼
checkcode = ""
for i in range(4):#4位驗證碼;參數為幾,就是幾位驗證碼
cur = random.randrange(0, 4)
#字母
if cur == i:
tmp = chr(random.randint(65,90))#將整數轉化為ascii碼
#數字
else:
tmp = random.randint(1,10)#1-9隨機選一位
checkcode += str(tmp)
print(checkcode)












python:random模塊