random

random

  • 取隨機數python

  • 取一個隨機浮點數。dom

import random
random.random()
0.9896051007555908
  • 在1-3取一個隨機數數(整型)。
a=random.randint(1,3)
b=random.randint(1,3)
c=random.randint(1,3)
print(a,b,c)
3 1 2
  • 在序列中隨機取一個元素。
e=random.choice('hello')
f=random.choice('hello')
g=random.choice('hello')
print(e,f,g)
e l l
  • 在序列中隨機取一個元素,指定元素的個數。
seq1=random.sample('hello',2)
seq2=random.sample('hello',2)
seq3=random.sample('hello',2)
print(seq1,seq2,seq3)
['l', 'h'] ['l', 'l'] ['e', 'h']
  • 打亂一個有序列表
ls1=[1,2,3,4,5,6]
random.shuffle(ls1)
print(ls1)
[5, 2, 6, 3, 4, 1]

使用random塊取隨機驗證碼

checkcode=''
for i in range(4):
    current=random.randint(0,9)
    checkcode+=str(current)
print(checkcode)
0346

字母加數字混合版

import random
checkcode1='' # 驗證碼寄存
for i in range(0,3): #三次 產生三組驗證碼,檢驗是否能生成
    for i in range (4):#執行次,產生4個隨機字符
        current=random.randrange(0,4)#隨機深沉一個數字和
        if current == i: # 用隨機數和循環次數猜
            tmp=chr(random.randint(65,90))# 猜中了幾生成一個字符
        else:
            tmp=random.randint(0,9)# 沒有猜中就生成一個數字
        checkcode1+=str(tmp) #將生成的字母或者數字添加到變量裏面
    print('驗證碼:',checkcode1)# 將生成的驗證碼打印出來
    checkcode1='' # 初始化驗證碼寄存器
驗證碼: 0497
驗證碼: 5C12
驗證碼: 3O3R

```code

相關文章
相關標籤/搜索