Home > Mobile >  How to take a user input of 24 hour time in HHMM format? (without importing any modules)
How to take a user input of 24 hour time in HHMM format? (without importing any modules)

Time:05-23

I need to accept a user input for time, between 0000 and 2359, without importing any modules. I currently have it just taking an int input:

fillTime = "X"
while fillTime == "X":
    try:
        fillTime = int(input("Enter the time (0000-2359): "))
        if fillTime < 0 or fillTime > 2359:
                print("Error! Please enter a valid time!")
                fillTime = "X"
        else:
            break
    except:
        print("An unknown error occurred!")

however this doesn't verify if the time is invalid (e.g. 1299 etc.) Any help would be greatly appreciated!

Edit fixed an error in my code, first line was wrong

CodePudding user response:

You can use the modulo operator to verify the last two digits. Also your loop should not check for "X". Just use while True and break:

while True:
    try:
        fillTime = int(input("Enter the time (0000-2359): "))
        if not (0 <= fillTime <= 2359) or fillTime % 100 > 59:
            print("Error! Please enter a valid time!")
        else:
            break
    except:
        print("An unknown error occurred!")
  • Related