python-3.xconditional-statementstry-except

Try-except statement not working in while loop


I wrote a program with the function convert_12_to_24 to convert 12hr time to 24hr time, however, the times were only defined in the program, and did not accept user input. I decided to upgrade the code by allowing the user to input a specific time for output and used a try-except statement to check for errors in user input.

def convert_12_to_24(hour,minute,meridiem):
    if (hour == 12) and (meridiem == 'PM'):
        print("12:" + str(minute))
    elif (hour == 12) and (meridiem == 'AM'):
        print("0:" + str(minute))
    elif (meridiem == 'PM'):
        hour_1 = int(hour) + 12
        print(str(hour_1) + ':' + str(minute))
    elif (meridiem == 'AM'):
        print(str(hour) + ":" + str(minute))

hour = input("Hour: ")
minute = input("Minute: ")
meridiem = input("AM or PM: ")

while True:

    try:
        convert_12_to_24(hour,minute,meridiem)
        break

    except:
        print("\n")
        print("Error, please input in the following manner: ")
        print("Hour: XX")
        print("Minute: XX")
        print("AM or PM: AM or PM")

However, when I run the code, the code doesn't rerun with an error, and the order of execution for the function conditionals is messed up. Any help would be appreciated.


Solution

  • I have modified your code:

    hour and minute should be converted to int type when asking user input

    If any of the conditions are not matching I am raising an error by returning 1/0 so the code falls back to except in try-except block.

    def convert_12_to_24(hour,minute,meridiem):
        if (hour == 12) and (meridiem == 'PM'):
            print("12:" + str(minute))
        elif (hour == 12) and (meridiem == 'AM'):
            print("0:" + str(minute))
        elif (meridiem == 'PM'):
            hour_1 = int(hour) + 12
            print(str(hour_1) + ':' + str(minute))
        elif (meridiem == 'AM'):
            print(str(hour) + ":" + str(minute))
        else:
            return 1/0
    
    hour = int(input("Hour: "))
    minute = int(input("Minute: "))
    meridiem = input("AM or PM: ")
    
    while True:
    
        try:    
            convert_12_to_24(hour,minute,meridiem)
            break
    
        except:
            print("\n")
            print("Error, please input in the following manner: ")
            print("Hour: XX")
            print("Minute: XX")
            print("AM or PM: AM or PM")
            break