python relational inclusive operators not inludind start and end values

50 views Asked by At

The goal of the function is to output a value in a given range. Including the start and end value if it is entered as input. The function only outputs the expected result for values at the start and between the range.

def main():
    #assume user input will be formatted in 24-hour time as #:## or ##:## 
    time = input("What is the time: ")

    if time >= "7.0" and time <= "8.0":
        print("breakfast time")
    elif time >= "12.0" and time <= "13.0":
        print("lunch time")
    elif time >= "18.0" and time <= "19.0":
        print("dinner time")

def convert(time):
    h, m = time.split(":")
    time = float(((float(h) * (60)) + float(m)) / 60)
    return time

if __name__ == "__main__":
    main()
  • current output when input is i.e 8:00 --> ""
  • expected output when input is i.e 8:00 --> breakfast
2

There are 2 answers

4
SWEEPY On BEST ANSWER

You need first to call you convert method, and change the conditions to avoid exception comparing string with float

def main():
    time = convert(input("What is the time: "))

    if time >= 7.0 and time <= 8.0:
        print("breakfast time")
    elif time >= 12.0 and time <= 13.0:
        print("lunch time")
    elif time >= 18.0 and time <= 19.0:
        print("dinner time")

def convert(time):
    h, m = time.split(":")
    time = float((int(h) * (60) + int(m)) / 60)
    return time

if __name__ == "__main__":
    main()
0
chepner On

Use datetime.strptime to parse text representations of times, then compare them to other time values.

from datetime import datetime, time


def main():
    #assume user input will be formatted in 24-hour time as #:## or ##:## 
    current_time = input("What is the time: ")
    
    current_time = datettime.strptime(current_time, "%H:%M").time()

    if time(7) <= now <= time(8):
        print("breakfast time")
    elif time(12) <= now <= time(13):
        print("lunch time")
    elif time(18) <= now <= time(19):
        print("dinner time")

if __name__ == "__main__":
    main()