生成隨機驗證碼的方法


1、借助列表

import random

def random_code():
    random_list = []
    for i in range(4):
        ra = random.randrange(4)
        if ra == i:
            random_list.append(chr(random.randrange(97,122)))
        else:
            random_list.append(str(random.randrange(0,9)))
    code = "".join(random_list)
    return code

result = random_code()
print(result)

  上述代碼實現了隨機驗證碼的功能,但是只能生成包含小寫字母的隨機驗證碼;並且我們也是借助列表完成的,字符串的拼接加上列表,字符串jion()方法,生成了隨機驗證碼。下面我們來嘗試也生成大寫驗證碼的方法。

import random

def random_code():
    random_list = []
    for i in range(4):
        ra = random.randrange(4)
        if ra == i:
            random_list.append(chr(random.randrange(97,122)))
        elif ra > i:
            random_list.append(str(random.randrange(0,9)))
        else:
            random_list.append(chr(random.randrange(65,90)))
    code = "".join(random_list)
    return code

result = random_code()
print(result)

  由於數據之間有三種關系,大於,小於,等於,這樣把每種情況都進行分析,就能生成三種隨機驗證碼;當等於的時候生成小寫驗證碼,等大於的時候生成數字,當小於的時候生成大寫字母驗證碼,這樣就實現了我們在網站上面常見的驗證碼的形式。

2、字符串拼接

import random

def verification_code():
    code = ""
    for i in range(1,5):
        ra = random.randint(1,4)
        if ra == i:
            string = chr(random.randrange(97,122))
        elif ra > i:
            string = chr(random.randrange(65,90))
        else:
            string = str(random.randint(0,9))
        code += string

    return code

result = verification_code()
print(result)

  此方法就是使用字符串的拼接生成的隨機驗證碼,其實上述方法的本質都是一樣的,可能第一種方法的效率還會更高一點,但是都實現了隨機驗證碼的功能。

二、生成賬單流水號的方法

 

import datetime,time

def serial_number():
    serial = "{0}{1}".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S"),str(int(time.time())))
    return serial

message = serial_number()
print(message)

 

  賬單流水號是由日期datetime模塊和time模塊構成,由於流水號就是當時購物的時間串號,而且永遠不會重復。

    time模塊中的起始時間是從1970年開始的

邏輯判斷函數:

 

def input_date(msg,default_date):
    '''
    對輸入的日期進行判斷是否正確,yyyy-mm--dd or yyyy-m-d
    :param msg:         輸入提示信息
    :param default_date:    默認日期
    :return:           返回日期str類型
    '''
    check_flag = False
    while not check_flag:
        strdate = input(msg).strip()
        if not strdate:       #如果用戶輸入的不是空,則不執行,如果用戶輸入的是空,則執行
            strdate = default_date
        try:
            date_list = strdate.split("-")
            print("\033[33mdate_list:{0}\033[0m".format(date_list))
            result = date(int(date_list[0]),int(date_list[1]),int(date_list[2]))
            print("\033[31mresult:{0}\033[0m".format(result))
            check_flag = True
        except ValueError:
            show_message("輸入日期不合法,請重新輸入!","ERROR")
            continue
    return result.strftime("%Y-%m-%d")

 

輸出如下:

請輸入您要確認的日期:
date_list:['2017', '5', '9']
result:2017-05-09
2017-05-09

上述代碼實現的是,將字符串的日期格式,轉換為真正的日期格式,上面代碼中:

date_list = strdate.split("-")
print("\033[33mdate_list:{0}\033[0m".format(date_list))
result = date(int(date_list[0]),int(date_list[1]),int(date_list[2])) print("\033[31mresult:{0}\033[0m".format(result))
上述代碼中,datetime模塊中的date()方法將數值轉換為日期格式,和Excel中的date()函數功能是一樣的

datetime模塊中的date()方法天生具有檢測日期輸入是否合法的功能,datetime.date(year,month,day)里面約定了month的范圍是1-12,同時day也是
有約定的,如下:
>>> datetime.date(2017,15,36)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: month must be in 1..12
>>> datetime.date(2017,12,40)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month
可以看出,如果月份,天數錯誤的話,會提示ValueError錯誤,這樣就能夠讓我們方便很多檢測錯誤,只要使用try,except就能讓用戶重新輸入正
確的日期。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM