Python程序运行后额外输出None的问题求助
问题原因及修复方案
问题根源
你的convert函数没有显式返回值,Python中函数默认会返回None。而你在main函数里将convert的返回值赋值给converted_time后,又执行了print(converted_time),这就导致程序额外输出了None。
修复方案一:让convert返回字符串,由main统一打印
修改代码,让convert函数返回对应的时间提示字符串,而非直接在函数内部打印:
def main(): time = input("What time is it: ") converted_time = convert(time) if converted_time: # 避免打印空字符串 print(converted_time) def convert(time): hours, minutes = time.split(":") new_hours = float(hours) if 7 <= new_hours <= 8: return "Breakfast Time" elif 12 <= new_hours <= 13: return "Lunch Time" elif 18 <= new_hours <= 19: return "Dinner Time" else: return "" if __name__ == "__main__": main()
修复方案二:直接调用convert,不处理其返回值
如果想保留convert内部的打印逻辑,只需在main里直接调用函数,不要打印它的返回值:
def main(): time = input("What time is it: ") convert(time) # 直接调用,无需处理返回值 def convert(time): hours, minutes = time.split(":") new_hours = float(hours) if 7 <= new_hours <= 8: print("Breakfast Time") elif 12 <= new_hours <= 13: print("Lunch Time") elif 18 <= new_hours <= 19: print("Dinner Time") # 移除else的空打印,避免输出多余空行 if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者23lliam
相关产品推荐
相关产品推荐

