python 如何重复判断输入的日期是否符合条件

怎么连续判断日期输入是否正确?
是否是有效日期
输入的是字符串
正确格式是
日/月/年

输入 2021/02/12
结果 输入不正确(请按 日/月/年 输入)

输入 35/13/2021
结果 35/13/2021 不是有效的日期

输入 28/02/2022
结果 输入正确!

while循环,内部大型if...else判断,简单的办法是用正则匹配,然后对个例进行分析,我这里给个逻辑比较易懂的例子,你看看:

while True:
    date = input("请输入一个日期,格式 月/日/年:")
    if len(date)==10: #标准格式长度为10
        date_arr = date.split("/") #用/分割字符串
        if len(date_arr)==3 and len(date_arr[0])==2 and len(date_arr[1])==2 and len(date_arr[2])==4: #分割为3段,每段的长度分别是2、2、4
            if date_arr[0].isdigit() and date_arr[1].isdigit() and date_arr[2].isdigit(): #年月日都需要是数字类型字符串
                m = int(date_arr[0]) #月转为数字
                d = int(date_arr[1]) #日转为数字
                y = int(date_arr[2]) #年转为数字
                if m>0 and m<13: #判断月份区间
                    if (m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12) and (d>0 and d<32): #31天的月
                        print("格式正确")
                        continue
                    elif (m==4 or m==6 or m==9 or m==11) and (d>0 and d<31): #30天的月
                        print("格式正确")
                        continue
                    elif m==2:
                        if (y%4==0 and y%100!=0) or y%400==0 and (d>0 and d<30): #闰年2月
                            print("格式正确")
                            continue
                        elif (y%4!=0 or (y%4==0 and y%100==0)) and (d>0 and d<29): #非闰年二月
                            print("格式正确")
                            continue
                        else:
                            print("输入内容有误,日数不对")
                    else:
                        print("输入内容有误,日数不对")
                else:
                    print("输入内容有误,月份不对")
            else:
                print("输入内容有误,非数字")
        else:
            print("输入内容有误,格式不匹配")
    else:
        print("输入内容有误,长度不符合")

img


如有帮助,请采纳

用while True循环做

while True保持连续重复输入
然后,
判断日期的话
date=input()
date = date.split('/')
if(len(date)!=3) 格式不正确
=3,对这三个部分进行对应的条件判断
都通过,就是正确的格式