判断有效日期
至少封装出4个函数
# coding=utf-8
# 判断用户输入是否合法
def is_legal_input(date):
# 如果长度不为8或者不是纯数字,则重新输入
if len(date) != 8 or not date.isdigit():
return False
else:
return True
# 判断是否是闰年
def is_leapyear(year):
if (year%4==0 and year%100!=0) or year%400==0:
return True
else:
return False
# 判断月数是否合法:
def is_legal_month(month):
# 判断月分是否合法
if month < 1 or month >12:
return False
else:
return True
# 判断日期是否合法
def is_legal_day(year, month, day):
# 下标即对应月份数
pingnian_month = [0,31,28,31,30,31,30,31,31,30,31,30,31]
runnian_month = [0,31,29,31,30,31,30,31,31,30,31,30,31]
if is_leapyear(year):
# 判断日期是否合法
if day<1 or day>runnian_month[month]:
return False # 不合法直接重新输入
else:
return True
else:
# 判断日期是否合法
if day<1 or day>pingnian_month[month]:
return False
else:
return True
# 主函数
def main():
while True:
date = input("请输入一个日期(8位):")
# 如果输入QUIT则退出
if date == "QUIT":
break
# 如果长度不为8或者不是纯数字,则重新输入
if not is_legal_input(date):
print("请输入一个有效的八位数日期,如20170327")
continue
else:
year = int(date[0:4]) # 截取年份
month = int(date[4:6]) # 截取月份,注int("02")--->2
day = int(date[6:]) # 截取日期
# 如果不合法,则重新输入
if not is_legal_month(month):
print("您输入的%s不是有效日期, 请重新输入"%date)
continue
if not is_legal_day(year, month, day):
print("您输入的%s不是有效日期, 请重新输入"%date)
continue
# 如果都合法,则打印以下信息
print("您输入的%s是有效日期"%date)
print("="*30)
main()