如何用Python实现无前导零军时600-1100判断并修复餐厅营业状态代码错误
Python 24小时制军时区间判断修正方案
原有代码错误原因
你写的time == 600-1100是错误语法:Python会先执行600-1100的减法运算得到结果-500,本质是判断输入时间是否等于-500,完全无法实现区间判断的需求。
正确区间判断规则
首先明确各营业时段的边界逻辑(可根据实际需求调整开闭区间):
- 早餐:600 ≤ 时间 < 1100
- 午餐:1100 ≤ 时间 < 1600
- 晚餐:1600 ≤ 时间 < 2300
- 其余时间闭店
修正后完整代码
print("Welcome to the Terrier Cafe! Enter the current time below and this program suggests a meal and a drink...") print() # 输入时间,转整型 time = int(input("Enter the current time of day using a 24-hour clock (do NOT use a leading zero): ")) # 区间判断逻辑 if 600 <= time < 1100: print("We are open!") print("We are serving breakfast.") print("We suggest a cup of coffee and eggs and bacon to start your day!") print("Thanks for choosing our restaurant.") elif 1100 <= time < 1600: print("We are open!") print("We are serving lunch.") print("We suggest a glass of soda and a crispy grilled cheese sandwich.") print("Thanks for choosing our restaurant.") elif 1600 <= time < 2300: print("We are open!") print("We are serving dinner.") print("We recommend a cold glass of water and a plate of rice and chicken.") print("Thanks for choosing our restaurant.") else: print("Sorry we're closed!") print("Thank you for choosing our restaurant.")
可选优化点
如果需要提升鲁棒性,可以增加输入合法性校验:
- 判断输入的时间是否在0~2359范围内
- 校验分钟部分不超过59(比如输入670这种无效时间可以给出错误提示)
内容的提问来源于stack exchange,提问作者user16865156
相关产品推荐
相关产品推荐

