【问题标题】:None is displayed whenever I run my program [duplicate]None is displayed whenever I run my program [duplicate]
【发布时间】:2022-12-27 22:32:32
【问题描述】:

Whenever I try to run my program it works but None is also being displayed after. Here is the code and the results I got.

def main():
    time = input("What time is it: ")
    converted_time = convert(time)
    print(converted_time)


def convert(time):
    hours,minutes = time.split(":")
    new_hours = float(hours)
    new_minutes = float(minutes)

    if new_hours >= 7 and new_hours <=8:
        print("Breakfast Time")
    elif new_hours >=12 and new_hours <=13:
        print("Lunch Time")
    elif new_hours >=18 and new_hours <=19:
        print("Dinner Time")
    else:
        print("")


if __name__ == "__main__":
    main()
What time is it? 7:00
answer: 
Breakfast Time
None


tried playing around with some of the print functions.

【问题讨论】:

标签: python python-3.x


【解决方案1】:

Your convert function has no return statement and therefore implicitly returns None. Therefore, None is the value assigned to converted_time, which you then print.

【讨论】:

  • Basic questions like this have usually been asked and answered. Please don't answer duplicate questions. Instead, find the duplicate and flag/vote to close
【解决方案2】:

The reason is you're both printing in the convert function, as well as taking it's return value and printing it. Since you don't return anything from within the convert function, "None" is implicitly returned, and that is printed. You can fix this code by removing the print(converted_time) call

【讨论】:

  • Basic questions like this have usually been asked and answered. Please don't answer duplicate questions. Instead, find the duplicate and flag/vote to close
【解决方案3】:

Does this fix your code?

def main():
    time = input("What time is it: ")
    converted_time = convert(time)
    print(converted_time)


def convert(time):
    hours, _ = time.split(":")
    new_hours = float(hours)

    if 7 <= new_hours <= 8:
        return "Breakfast Time"
    if 12 <= new_hours <= 13:
        return "Lunch Time"
    if 18 <= new_hours <= 19:
        return "Dinner Time"
    return ""


if __name__ == "__main__":
    main()

Output:

What time is it: 7:00
Breakfast Time

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2022-12-26
    • 2022-12-02
    • 2022-12-02
    • 2022-12-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多