標籤:python產生隨機密碼 random模組產生隨機密碼
一、產生隨機驗證碼(純數字及字母加數字):
import randomimport stringcheckcod=‘‘for i in range(5): #5位驗證碼 ‘‘‘ #純數字驗證碼 #隨機值1-9取可以保證5位,如果是1-12就會出現5位以上驗證碼 current=random.randint(1,9) #i資料類型轉換成字串類型 #checkcod+=str(i) checkcod+=str(current) ‘‘‘ #數字加字母驗證碼 迴圈5次:猜的值和當前迴圈i值是否相等 current=random.randrange(0,5) if current == i: #猜的值與當前i迴圈值相等就會執行下面tmp值為字母 tmp=chr(random.randint(65,90)) #把十進位數字轉換成字母用chr(65到90是擷取大寫字母 #chr(65)是大A chr(90)是大寫 #擷取65到90用random.randint() else: # 否則就是猜的值與當前i值不相等,就會是純數字 tmp=random.randint(0,9) checkcod+=str(tmp)print(checkcod)
二、產生隨機驗證碼(字母加數字):
import randomcheckcode = ‘‘for i in range(4): current = random.randrange(0,4) if current != i: #!= 不等於 - 比較兩個對象是否不相等 temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp)print (checkcode)
用!=這個方法擷取的值是字母+數字,而==這個方法是有時迴圈為數字+字母、有時迴圈為純數位。
python產生隨機驗證碼