简体   繁体   English

如何在 Python function 返回 boolean 中使用 try-except?

[英]How to use try-except in Python function return boolean?

I need to use try-except to validate the input string of a date and time.The input format should be MM/DD/YYYY HH:MM:SS.我需要使用 try-except 来验证日期和时间的输入字符串。输入格式应该是 MM/DD/YYYY HH:MM:SS。 If the validate function returns false, then it's not valid.I tried a invalid input, but the try-except didn't work as expected.如果验证 function 返回 false,则它无效。我尝试了无效输入,但 try-except 没有按预期工作。 The error message wasn't printed.未打印错误消息。 What's wrong with my code?我的代码有什么问题? How to fix it?如何解决? Thanks.谢谢。

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!")

The except will only catch an exception if one is thrown and not caught by an earlier try-except .只有在抛出异常并且没有被早期的try-except捕获时, except才会捕获异常。 You are not raise ing anything in your code, so the except block will never run.你没有在你的代码中raise任何东西,所以except块永远不会运行。 You should instead throw an error, perhaps a ValueError , when the validate_user_input function returns False :validate_user_input function 返回False时,您应该抛出一个错误,也许是ValueError

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

Use an if statement instead.请改用 if 语句。 This should be simpler than using try and except.这应该比使用 try 和 except 更简单。

if validate_user_input(input) == False:
    print("Your input is valid!")
else:
    print("Error: the input date and time is invalid!")
# try-except
try: 
    validate_user_input(input) == False
    print("Your input is valid!")
except:
    print("Error: the input date and time is invalid!")

Seems like you're going to validate the entered date & time from the input.似乎您要从输入中验证输入的日期和时间。 But this code lines doesn't do anything.但是这个代码行没有做任何事情。 It check the condition without doing anything, @dogman288 answer make it happen.它检查条件而不做任何事情,@dogman288 回答让它发生。 I would like to suggest a library call python-dateutil .我想建议一个库调用python-dateutil Within few lines you can do your validations very easily, I hope this will save your time.只需几行,您就可以非常轻松地进行验证,我希望这会节省您的时间。 Just comment the relevant outputs.只需评论相关输出。

from dateutil.parser import parse
from dateutil.parser._parser import ParserError


def validate_user_input(input_string: str):
    try:
        parse(input_string)
        print("Your input is valid!")
    except ParserError as error:
        print(error)


validate_user_input("12/31/2005 23:59:6")  # Your input is valid!
validate_user_input("13/31/2005 23:59:6")  # month must be in 1..12: 13/31/2005 23:59:6
validate_user_input("12/32/2005 23:59:6")  # day is out of range for month: 12/32/2005 23:59:6
validate_user_input("12/31/200511111 23:59:6")  # year 200511111 is out of range: 12/31/200511111 23:59:6
validate_user_input("12/31/2005 24:59:6")  # hour must be in 0..23: 12/31/2005 24:59:6
validate_user_input("12/31/2005 23:61:6")  # minute must be in 0..59: 12/31/2005 23:61:6
validate_user_input("12/31/2005 23:59:61")  # second must be in 0..59: 12/31/2005 23:59:61
validate_user_input("")  # String does not contain a date: 
validate_user_input("some_string")  # Unknown string format: some_string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM