1. 程式人生 > >python--random模組(產生隨機值)、洗牌、驗證碼應用

python--random模組(產生隨機值)、洗牌、驗證碼應用

前言:
在python中用於生成隨機數的模組是random,在使用前需要import

  • random.random():生成一個0-1之間的隨機浮點數.
  • random.uniform(a, b):生成[a,b]之間的浮點數.
  • random.randint(a, b):生成[a,b]之間的整數.
  • random.randrange(a, b, step):在指定的集合[a,b)中,以step為基數隨機取一個數.如random.randrange(0, 20, 2),相當於從[0,2,4,6,…,18]中隨機取一個.
  • random.choice(sequence):從特定序列中隨機取一個元素,這裡的序列可以是字串,列表,元組等,例:
    string = 'nice to meet you'
    tup = ('nice', 'to', 'meet', 'you')
    lst = ['nice', 'to', 'meet', 'you']
    print random.choice(string)
    print random.choice(tup)
    print random.choice(lst)
  • random.shuffle(lst):將列表中的元素打亂,洗牌
  • random.sample(sequence,k):從指定序列在隨機抽取定長序列,原始序列不變
    string2 = 'nice to meet you'
    lst3 = ['nice', 'to', 'meet', 'you']
    print random.sample(string2, 2)
    print random.sample(lst3, 2)

應用一**洗牌:

import random
lst2 = ['nice', 'to', 'meet', 'you']
# 直接print,會返回為空
# print random.shuffle(lst2) random.shuffle(lst2) print lst2 輸出結果為: ['you', 'meet', 'nice', 'to']

應用二**生成隨機的4位數字驗證碼:

import random
auth = ''
for i in range(0, 4):
    current_code = random.randint(0, 9)
    auth += str(current_code)
print auth

應用三**生成隨機的4位字母驗證碼:

auth2 = ''
for ii in range(0, 4
): current_code = random.randint(65, 90) # ord()函式主要用來返回對應字元的ascii碼, # chr()主要用來表示ascii碼對應的字元他的輸入時數字 auth2 += chr(current_code) print auth2

應用四**生成隨機的4位字母、數字驗證碼:

auth3 = ''
for j in range(0, 4):
    current = random.randint(0, 4)
    if j == current:
        current_code = random.randint(0, 9)
    else:
        current_code = chr(random.randint(65, 90))
    auth3 += str(current_code)
print auth3