编写麦当劳菜单Python程序遇异常:输入McRoyal未返回对应价格
问题诊断与修复
核心错误
你代码里的判断逻辑完全搞反了:你把价格变量McRoyal转成字符串(变成"19.99"),然后去检查这个价格字符串是否存在于用户输入的餐品名称里——用户输入的是"McRoyal",自然匹配不上,所以程序会执行else分支。
修复后的代码
theOrder = input("Hello, welcome to McDonald's, what can i get for you today? ") McRoyal_price = 19.99 McChicken_price = 9.99 if "McRoyal" in theOrder: print(f"That would be ${McRoyal_price}") elif "McChicken" in theOrder: print(f"That would be ${McChicken_price}") else: print("That's not on the menu")
关键修改点
- 修正判断逻辑:把
str(McRoyal) in theOrder改成"McRoyal" in theOrder,用餐品名称字符串去匹配用户输入,而不是价格的字符串。 - 优化变量名(可选但推荐):将
McRoyal更名为McRoyal_price,让变量名清晰区分餐品名称和对应价格,避免混淆。 - 补充
elif分支:支持识别菜单里的McChicken选项,符合你预设的菜单需求。
额外优化建议(可选)
如果想让程序兼容大小写不同的输入(比如用户输入mcroyal或MCROYAL也能识别),可以把输入转成统一小写后再判断:
theOrder = input("Hello, welcome to McDonald's, what can i get for you today? ").lower() McRoyal_price = 19.99 McChicken_price = 9.99 if "mcroyal" in theOrder: print(f"That would be ${McRoyal_price}") elif "mcchicken" in theOrder: print(f"That would be ${McChicken_price}") else: print("That's not on the menu")
内容的提问来源于stack exchange,提问作者RyRyCodz
相关产品推荐
相关产品推荐

