收到“KeyError:1”,为什么会发生这种情况,我如何修复它?

2024-09-28 18:54:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一段代码,用于返回用户要求的比萨饼配料。 代码如下:

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循环有关,因为这是我收到此错误之前添加的最后一个内容。我花了一些时间研究这个问题,但是我没有找到任何有用的东西

我的问题: 为什么我总是遇到这个问题,我如何才能解决它,这样我就不会再犯这个错误了

先谢谢你


Tags: 代码用户yourresponse错误dototalmappings
3条回答

这是错误的

 requested_toppings.append(requested_toppings)

应该是

 requested_toppings.append(toppings_wanted)

您需要将int作为输入

response = int(input('-'))

你有一个额外的'

12: 'Jalapenos''
  • response = input('-')这里的input函数将返回str

  • 您的dicttopping_mappings此处的键为int。因此,您需要在此toppings_wanted = topping_mappings[toppings_wanted]之前转换为int

  • 以下更改是修复它的一种方法

response = input('-')
toppings_wanted = int(response) if response.isdigit() else None
toppings_wanted = topping_mappings[toppings_wanted]

在这里,我编辑并添加了您错误的评论

'def topping_menu(): 打印(“”) 你的比萨饼要加什么配料

    _____________________________________________________
   |   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('-')
    if response == 'q':#Checking for Quit
        break
    toppings_wanted = response
    toppings_wanted = topping_mappings[int(toppings_wanted)]#Converting response to int
    requested_toppings.append(toppings_wanted)
    

    

    #for requested_topping in requested_toppings: 
    #You dont need the for loop
    if toppings_wanted in topping_mappings.values():#You were not comparing it with Values
        print(f"Adding: {toppings_wanted}") #This should be toppings wanted

    else:
        print(f"We do not have {toppings_wanted}") #This also should be toppings wanted
topping_total = len(requested_toppings) * float(1.23) #You dont have to write float python knows its float by default

print("\nWe are adding the requested toppings to your pizza.")
print(f"your topping total will be: ${topping_total}")

`

相关问题 更多 >