Python while循环不会停止

时间:2015-04-28 23:51:44

标签: python-2.7 date while-loop

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

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

1 个答案:

答案 0 :(得分:2)

您永远不应该使用except,始终检查特定的例外:

except ValueError:

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

相关问题