gpt4 book ai didi

python - 循环出现问题并避免崩溃

转载 作者:行者123 更新时间:2023-12-01 04:37:41 26 4
gpt4 key购买 nike

我在循环这个程序时遇到了麻烦...我想询问他们是否提供了错误格式的字符串或日期...这是我的代码,我不知道为什么它不起作用。每次我运行它并输入一个字符串时,第一次它会说“哎呀!这不是一个有效的日期。再试一次...”如果用户再次输入错误的输入,它就会崩溃

<小时/>

这是我的代码。

while 1 == 1:
try:
birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
birth_date = datetime.strptime(birthday, '%m/%d/%Y')

except ValueError:
print "Oops! That was not a valid date. Try again..."
birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
birth_date = datetime.strptime(birthday, '%m/%d/%Y')

if (((datetime.today() - birth_date).days)/365.2425) > 110:
print "Sorry You are older than 110 year i cannot do that math."

elif ((datetime.today() - birth_date).days) < 0:
print "Sorry you entered a date in the furture."

elif ((datetime.today() - birth_date).days) == 0:
print "OMG You were just born, tomorrow you will be one day old."
else:
print "Age: %d days " % ((datetime.today() - birth_date).days)

这是它显示的错误:

birth_date = datetime.strptime(birthday, '%m/%d/%Y')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'ASFA' does not match format '%m/%d/%Y'
logout

最佳答案

好吧,你没有什么可以捕获 except block 中的错误。你可能想要那个:P

尝试:

while True: #Don't need 1==1, while True works too!
try:
birthday = raw_input("Enter your Birth date in MM/DD/YYYY format: ")
birth_date = datetime.strptime(birthday, '%m/%d/%Y')

except ValueError:
print "Oops! That was not a valid date. Try again..."
#Because everything else is in an else block, now goes back
#to start of loop
else:
#only happens if no exceptions happen
if (((datetime.today() - birth_date).days)/365.2425) > 110:
print "Sorry You are older than 110 year i cannot do that math."
#rest of your elif tree goes here, etc, etc.
else: #I'm valid data! Finally!
break
birth_date #do your calculations here, outside the loop?

关于python - 循环出现问题并避免崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31457102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com