How to work with am/pm with the time 12 or 24 in python?

Viewed 37

I'm relatively new to python and I've tried to implement program to prompt user to input time (##:## a.m./p.m.) and output if it's breakfast (7 a.m. to 8 a.m.), lunch (12 p.m to 1 p.m.), or dinner time (6 p.m. to 7 p.m.).

it worked for the most part but when i input 12:00 p.m., it doesn't output 'lunch' as it should. How can i fix this?

Any help would be appreciated.

Also how can I make it pythonic? Thanks again!

def main():
    time = input("whats the time? ")
    
    ans = (convert(time))
    if 7 <= ans <= 8: print ("breakfast time")
    elif 12 <= ans <= 13: print ("lunch time")
    elif 18 <= ans <= 19: print ("dinner time")
    else: return

def convert(x):
    h, m = x.split(":")
    new_m, time_range = m.split(" ")
    
    if "p.m." in m: 
        new_h = float(h) + 12
        y = new_h + float(new_m)/60
        return y
    elif "a.m." in m:
        new_h = float(h)
        y = new_h + float(new_m)/60
        return y
    else:
        return

main()
1 Answers

Since you are giving the input 12:00 pm, the convert function returns 24.00. In your main function there is no condition statement to check after 19.

Related