1. 程式人生 > >隨機生成模塊

隨機生成模塊

div 圖片 生成 pri 基數 span none open int

import random

print(random.randint(1,4))#從1到4隨機生成一個數字

print(random.randrange(1,4))#從1到3隨機生成一個數字,不包含3
print(random.randrange(1,10,2))#1到9隨機生成一個基數
print(random.randrange(0,10,2))#1到9隨機生成一個偶數

print(random.random())#隨機生成一個浮點數,範圍是0-1之間
print(random.uniform(1,3))#隨機生成一個浮點數,範圍能夠指定

print(random.choice("hello
"))#從字符串隨機取一個值 print(random.choice("hello"))#從字符串隨機取一個值 print(random.choice([1,2,3,4,5,6,7]))#從列表裏隨機取一個值 print(random.sample("hello",2))#從裏面隨機取兩個值 a = [1,2,3,4,5,6,7] random.shuffle(a)#對上面的數據進行洗牌,隨機打亂順序 print(a)

技術分享圖片
#隨機生成四位數字
import random
checkcode = ""
for i in range(4):
    temp = random.randint(1,9)
    checkcode 
+=str(temp) print(checkcode)
隨機生成四位數字

技術分享圖片
#隨機生成四位字符串,可能含有數字以及字母
import random
checkcode = ""
for i in range(4):
    current = random.randint(1,4)
    if i == current:
        tmp = chr(random.randint(65,90))#assic65到90範圍對應大寫A到Z,chr將對應數字轉換為assic
    else:
        tmp = random.randint(1,9)
    checkcode 
+=str(tmp)#隨機生成的為數字,所以需要轉換為字符串 print(checkcode)
隨機生成四位字符串,可能含有數字以及字母

隨機生成模塊