Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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!")
like image 941
Timon Avatar asked Apr 22 '26 10:04

Timon


1 Answers

The except will only catch an exception if one is thrown and not caught by an earlier try-except. You are not raiseing anything in your code, so the except block will never run. You should instead throw an error, perhaps a ValueError, when the validate_user_input function returns False:

try:
    if not validate_user_input(input):
        raise ValueError("Bad input")
except:
    ...
like image 179
dogman288 Avatar answered Apr 25 '26 00:04

dogman288



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!