Python-none从try和except子句返回
此代码(日期)的返回为“无”。如果提供了无效条目,则提供了有效条目。但是,如果第一次提供有效条目,则会提供正确的日期报税表。关于如何解决这个问题有什么建议吗Python-none从try和except子句返回,python,function,validation,date,try-except,Python,Function,Validation,Date,Try Except,此代码(日期)的返回为“无”。如果提供了无效条目,则提供了有效条目。但是,如果第一次提供有效条目,则会提供正确的日期报税表。关于如何解决这个问题有什么建议吗 def getDate(): date = input("Please enter the date in DD/MM/YYYY format: ") try: strptime(date, "%d/%m/%Y") return date except: print (
def getDate():
date = input("Please enter the date in DD/MM/YYYY format: ")
try:
strptime(date, "%d/%m/%Y")
return date
except:
print ("Invalid Date, please enter again")
getDate()
由于有这么多错误的答案被张贴到这个问题上,我觉得有必要再补充一个。在except子句中添加
return getDate()
,将使其按您所希望的那样工作:
def getDate():
date = input("Please enter the date in DD/MM/YYYY format: ")
try:
strptime(date, "%d/%m/%Y")
return date
except:
print ("Invalid Date, please enter again")
return getDate()
但是,使用递归处理重试并不理想。改为使用循环:
from time import strptime
def getDate():
while True:
date = input("Please enter the date in DD/MM/YYYY format: ")
try:
strptime(date, "%d/%m/%Y")
return date
except ValueError:
print ("Invalid Date, please enter again")
1.除了案例外,
中不返回任何内容。2.3.不要对此使用递归-请参阅,您可以通过将除
子句中的最后一行更改为return getDate()
使其工作。但正如jonrsharpe指出的那样,您不应该使用递归来执行重试;改为使用循环。结束此问题的原因似乎完全错误。它可以复制,而且(可能)不是打字错误。您不需要返回strtime(日期,“%d/%m/%Y”)
而不是返回日期
?不需要。strtime
调用只是为了确保date
是有效的(正确格式)日期字符串。@JamieBull:为什么strtime()
仅用于验证用户输入的字符串,函数返回字符串,而不是返回任何对象strtime()
返回的字符串(在我的情况下是time.struct\u time
)。顺便说一句,我会将返回日期
放在else
@TigerhawkT3:为什么?在这种情况下有区别吗?