gpt4 book ai didi

python - 如何在 Python 函数返回 boolean 值中使用 try-except?

转载 作者:行者123 更新时间:2023-12-04 00:55:14 25 4
gpt4 key购买 nike

我需要使用 try-except 来验证日期和时间的输入字符串。输入格式应为 MM/DD/YYYY HH:MM:SS。如果验证函数返回 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!")

最佳答案

except 只会捕获一个异常,如果一个异常被抛出并且没有被更早的 try-except 捕获。您没有在代码中raiseing 任何内容,因此except block 永远不会运行。当 validate_user_input 函数返回 False 时,您应该抛出错误,也许是 ValueError:

try:
if not validate_user_input(input):
raise ValueError("Bad input")
except:
...

关于python - 如何在 Python 函数返回 boolean 值中使用 try-except?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63007723/

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