Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading