Python虚拟咖啡店程序问题:输入无法匹配字典键,直接进入ELSE分支
问题分析与解决方案
核心问题
你的代码里,菜单字典的键是首字母大写格式(比如'Chicken Nuggets'),但你把用户输入转成了全小写(order.lower()),两者格式不匹配,导致order.lower() in menu永远为False,程序必然走else分支。
修复方案
需要在判断时将字典的键转为小写与输入匹配,同时保留原键格式,确保后续能正确从字典取值。修改while True循环内的代码如下:
while True: order = input("\nwhat would you like to order?\n") lower_order = order.lower() # 遍历菜单找到格式匹配的原键 matched_item = None for item in menu: if item.lower() == lower_order: matched_item = item break if matched_item: otime = menu[matched_item]['cook_time'] # 注意:otime是整数,拼接字符串前需转成str类型 print_with_typing(f"\nThank you {name} I will be right out with your order, the {matched_item} will be ready in {str(otime)}\n\n") break else: time.sleep(1) print(f"\nSorry {name} we aren't serving {order}, please select one of the following items from our menu:\n") for item in menu: print(item)
额外修复点
原代码中输出烹饪时长时,otime是整数类型,直接和字符串拼接会触发类型错误,修复代码里已通过str(otime)解决该问题。
简化优化(可选)
提前创建小写键到原键的映射字典,提升匹配效率:
# 定义menu后添加如下代码 lower_menu_map = {item.lower(): item for item in menu} # 循环内判断逻辑简化为 while True: order = input("\nwhat would you like to order?\n") lower_order = order.lower() if lower_order in lower_menu_map: matched_item = lower_menu_map[lower_order] otime = menu[matched_item]['cook_time'] print_with_typing(f"\nThank you {name} I will be right out with your order, the {matched_item} will be ready in {str(otime)}\n\n") break else: time.sleep(1) print(f"\nSorry {name} we aren't serving {order}, please select one of the following items from our menu:\n") for item in menu: print(item)
内容的提问来源于stack exchange,提问作者Apis
相关产品推荐
相关产品推荐

