2017-02-17 39 views
0

用于分配的指令是:“进行购买”在Python教程Codecademy网站

定义一个函数compute_bill它有一个参数food作为输入。 在函数中,创建初始值为零的变量total。 对于食物列表中的每个项目,将该项目的价格添加到总计。 最后,返回总数。 忽略您要结算的商品是否有库存。

请注意,您的功能应适用于任何食物清单。

以下是我试图解决这个问题

shopping_list = ["banana", "orange", "apple"] 

stock = { 
    "banana": 6, 
    "apple": 0, 
    "orange": 32, 
    "pear": 15 
} 

prices = { 
    "banana": 4, 
    "apple": 2, 
    "orange": 1.5, 
    "pear": 3 
} 
def compute_bill(food): 
    total=0 
    for item in food: 
     for items in prices: 
     if food[item]==prices[items]: 
      print prices[item] 
      total+=prices[item] 
     else: 
      print 'not found' 
    return total 
compute_bill(['apple', 'jok']) 

我得到的错误是:

Traceback (most recent call last): File "python", line 26, in File "python", line 21, in compute_bill KeyError: 'jok'

我把随机列表与“JOK”它,因为它表示任何名单。有人可以帮我吗?

回答

1

您正面临的错误是因为您试图从您的字典中获得不包含该密钥的项目jok的价格。

为了避免这个错误,这是最好的检查,如果你正在检查的重点存在,就像这样:

if item in prices: 
      total+= prices[item] 

所以给出的代码应该是这样的:

shopping_list = ["banana", "orange", "apple"] 

stock = { 
    "banana": 6, 
    "apple": 0, 
    "orange": 32, 
    "pear": 15 
} 

prices = { 
    "banana": 4, 
    "apple": 2, 
    "orange": 1.5, 
    "pear": 3 
} 
def compute_bill(food): 
    # Set total variable to 0 
    total=0 
    # Loop over every item in food list to calculate price 
    for item in food: 
     # Check that the item in the food list really exists in the prices 
     # dicionary 
     if item in prices: 
      # The item really exists, so we can get it's price and add to total 
      total+= prices[item] 
    print total 
compute_bill(['apple', 'jok', 'test', 'banana']) 
0

食物是一个列表,而不是一本字典 - 所以你不能通过列表中的索引以外的任何东西查找列表中的一个项目。但是,由于您已经对它进行了迭代,因此无需重新查找该项目。

你这样需要改变也

for items in prices: 
if food[item]==prices[items]: 

应该只是

for key, val in prices.items(): 
    if item == key: 

但仍然没有意义也不能迭代一个字典,而不是你只需要找到如果该项目在字典中,则输出

for item in food: 
    price = prices.get(item) 
    if price: 
     total+=price