Python while 循环不停止

Python while loop does not stop

我正在编写一个脚本来要求用户输入日期。如果是日期格式,则return条目;否则,继续。但是即使用户输入有效,我的代码也不会停止。有人可以分享一些见解吗?谢谢!

def date_input(prompt):
    while True:
        date_text = raw_input(prompt)
        try:           
            datetime.datetime.strptime(date_text, '%Y-%m-%d')
            return date_text
        except:
            print('Invalid input.')
            continue

你不应该使用 except,总是检查特定的异常:

except ValueError:

那么你真正的错误应该出现了。我怀疑你没有导入 datetime.