天天看點

判斷年月日是否正确

# 使用者輸入八位日期
date = input('請輸入八位年月日(如20180405):')
# 分割年月日
day = int(date[-2:])
month = int(date[4:6])
year = int(date[:4])
print(year, month, day)
# 定義閏年開關
if year % 4 == 0 and year % 100 != 100 or year % 400 == 0:
    print('%d年是閏年' % year)
    isRunNian = True
else:
    print('%d不是閏年' % year)
    isRunNian = False
# 判斷是否是閏年
if isRunNian:
    # 判斷月
    if month in [x for x in range(1, 13)]:
        monthmaxd = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        # 判斷日
        if day <= monthmaxd[month]:
            print('有效日期')
        else:
            print('不是有效日期,日錯誤')
    else:
        print('不是有效日期,月錯誤')
else:
    # 判斷月
    if month in [x for x in range(1, 13)]:
        monthmaxd = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        # 判斷日
        if day <= monthmaxd[month]:
            print('有效日期')
        else:
            print('不是有效日期,日錯誤')
    else:
        print('不是有效日期,月錯誤')