python2.7 - codecademy中A Day at the Supermarket遇到问题

查看:116
本文介绍了python2.7 - codecademy中A Day at the Supermarket遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

1、题目

While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.
我理解的意思是:利用循环计算出food中所有物品的总价格,但是我们在求价格的时候,先判断在stock(库存)字典中对应的值是否大于0,如果是的话才进行求和并且把stock对应的value值减一,我的代码如下:

2、我的代码

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 key in food:
        if stock[key] > 0:
            total = total + prices[key]
            stock[key] = stock[key] - 1
    return total

print compute_bill(shopping_list)
print stock

我的代码运行后输出为:

5.5
{'orange': 31, 'pear': 15, 'banana': 5, 'apple': 0}

3、错误提示

Oops, try again. stock doesn't look quite right! Make sure to not call compute_bill since it changes the stock! It should contain: {'orange': 32, 'pear': 15, 'banana': 6, 'apple': 0}

4、我去网上查过,这个问题的解决方法是

def compute_bill(shopping_list):
    total=0
    for items in shopping_list:
        if stock[items] != 0: 
            total+= prices[items];
            stock[items] -= 1;
    return total

5、不理解的地方

我使用print进行函数调用,而正确做法直接传递了参数,这两种方式有什么本质上的不同?我不明白为什么会报出那个错误呢?

解决方案

参考 http://stackoverflow.com/questions/23203606/codecademy-supermarket-subtract-error

删除 print compute_bill(shopping_list)这句好了

报错是叫你在自己的code里别调用compute_bill.估计是网站校验你答案的时候自己会做一些东西吧

这篇关于python2.7 - codecademy中A Day at the Supermarket遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆