我目前正在编写一段代码,用于返回用户要求的比萨饼配料。 代码如下:
def topping_menu():
print("""
What toppings do you want on your pizza?
_____________________________________________________
| 1:Bacon | 5:Anchovies | 9:Black Olives |
| 2:Pepperoni | 6:Spinach | 10:Chicken |
| 3:Mushrooms | 7:Onion | 11:Ground Beef |
| 4:Pineapple | 8:Bell Peppers | 12:Jalapenos |
|________________|__________________|_________________|
What toppings do you want on your pizza?
""")
def topping_order():
topping_mappings = {
1: 'Bacon',
2: 'Pepperoni',
3: 'Mushrooms',
4: 'Pineapple',
5: 'Anchovies',
6: 'Spinach',
7: 'Onions',
8: 'Bell Peppers',
9: 'Black Olives',
10: 'Chicken',
11: 'Ground Beef',
12: 'Jalapenos''
}
requested_toppings = []
while True:
response = input('-')
toppings_wanted = response
toppings_wanted = topping_mappings[toppings_wanted]
requested_toppings.append(requested_toppings)
if response == 'q':
break
for requested_topping in requested_toppings:
if requested_topping in topping_mappings:
print(f"Adding: {toppings_wanted}")
else:
print(f"We do not have {requested_topping}")
topping_total = len(requested_toppings) * float(1.23)
print("\nWe are adding the requested toppings to your pizza.")
print(f"your topping total will be: ${topping_total}")
topping_menu()
topping_order()
但是,当我运行代码时,会出现以下错误:
toppings_wanted = topping_mappings[toppings_wanted]
KeyError: '1'
当用户输入“1”时,代码应已返回:
Adding: Bacon
-q
We are adding the requested toppings to your pizza.
your topping total will be: $1.23
我猜这个问题与“topping_映射”或while循环有关,因为这是我收到此错误之前添加的最后一个内容。我花了一些时间研究这个问题,但是我没有找到任何有用的东西
我的问题: 为什么我总是遇到这个问题,我如何才能解决它,这样我就不会再犯这个错误了
先谢谢你
这是错误的
应该是
您需要将int作为输入
你有一个额外的'
response = input('-')
这里的input
函数将返回str
您的dict
topping_mappings
此处的键为int
。因此,您需要在此toppings_wanted = topping_mappings[toppings_wanted]
之前转换为int
以下更改是修复它的一种方法
在这里,我编辑并添加了您错误的评论
'def topping_menu(): 打印(“”) 你的比萨饼要加什么配料
def topping_order():
`
相关问题 更多 >
编程相关推荐