python之判斷合法日期


年月日分別為自定義函數的參數,判斷某一個日期是否為合法的日期;
如: 2020年12月33日不是合法的日期
2021年2月29日是不合法的日期

看代碼:方法一
def fn3(year, month, day):
    if month > 12 or month <= 0:
        return "%s年%s月%s日不是合法日期"%(year,month,day)
    if num_6(year):
        months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if day <= months[month-1]:
            return "合法日期"
        else:
            return "%s年%s月%s日不是合法日期" % (year, month, day)
    else:
        month2 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if day <= month2[month - 1]:
             return "合法日期"
        else:
            return "%s年%s月%s日不是合法日期" % (year, month, day)

# print(fn3(2020, 1, 31))
#方法二
def youhua(year, month, day): if month < 1 or month >12: return False days = 31 if month in [4,6,9,11]: days = 30 elif month == 2: if num_6(year): days = 29 else: days = 28 if day < 1 and day>days: return False return True # print(youhua(2020, 1, 31))

兩種方法,前面的思路更加復雜
后面的復雜度會好很多,哎,邏輯思維還需要提高....................
寫代碼太難了,沖沖沖


免責聲明!

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



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