python_Daily practice (每日一练) 63

判断有效日期
至少封装出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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值