我需要使用try-except来验证日期和时间的输入字符串。输入格式应为MM/DD/YYYY HH:MM:SS。如果validate函数返回false,则它无效。我尝试了无效的输入,但try-except没有按预期工作。没有打印错误消息。我的代码怎么了?如何修复它?谢谢
def validate_user_input(input_string):
# check the input validation
validation = True
if input_string[2] != "/" or input_string[5] != "/":
validation = False
elif int(date) > 31 or int(date) < 1:
validation = False
elif int(month) > 12 or int(month) < 1:
validation = False
elif int(hour) < 0 or int(hour) > 24:
validation = False
elif int(minute) < 0 or int(minute) > 59:
validation = False
elif int(second) < 0 or int(second) > 59:
validation = False
return validation
input = input("Please input a date and time within the format of MM/DD/YYYY HH:MM:SS")
# get the information from the input
year = input[6:10]
month = input[0:2]
date = input[3:5]
hour = input[11:13]
minute = input[14:16]
second = input[17:19]
# try-except
try:
validate_user_input(input) == False
print("Your input is valid!")
except:
print("Error: the input date and time is invalid!")
改用if语句。这应该比使用try和except更简单
似乎您要验证输入的日期&;输入的时间。但是这些代码行没有任何作用。它不做任何事情就检查情况,@dogman288回答:让它发生。我想建议图书馆打电话python-dateutil。在几行代码中,您可以非常轻松地进行验证,我希望这将节省您的时间。只需评论相关输出
except
仅当一个异常被抛出而未被较早的try-except
捕获时,才会捕获该异常。代码中没有raise
任何内容,因此except
块永远不会运行。当validate_user_input
函数返回False
时,您应该抛出一个错误,可能是ValueError
:相关问题 更多 >
编程相关推荐