-1

谁能帮助理解为什么computeBill函数中的循环没有迭代?

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

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

prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}

def computeBill(food):
    total = 0.0
    for item in food:
        total += prices[str(item)] + stock[str(item)]
        print total
        return total

computeBill(groceries)
4

6 回答 6

6

您在循环return 内部调用是因为它当前缩进的位置,所以它在第一次迭代后被执行。可能您想将它移到循环之外(与自身相同的缩进级别for),以便在迭代完成后调用它:

def computeBill(food):
    total = 0.0
    for item in food:
        total += prices[str(item)] + stock[str(item)]
        print total

    return total
于 2013-02-05T17:08:14.590 回答
1

return的语句在语句下方缩进for。解决这个问题,你应该没事。

于 2013-02-05T17:08:44.083 回答
1

您的返回行与 for 循环缩进。它将在第一个循环后返回。取消缩进该行,就可以了。

于 2013-02-05T17:08:46.437 回答
1

您不应return在循环中使用该语句,for而应在同一级别使用该语句。

于 2013-02-05T17:09:58.900 回答
0

为了使其工作,您需要将“return total”行放在与 for 循环相同的级别但不在其中,或者如果您想在每次迭代后打印出总数,则完全省略它。它不迭代的原因是 return 语句导致你的函数退出并将一个值返回给它的调用者。所以基本上,你有:

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

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

prices = {"banana": 4,    "apple": 2,
    "orange": 1.5,    "pear": 3
    }

def computeBill(food):
    total = 0.0
    for item in food:
        total += prices[str(item)] + stock[str(item)]
        print total

computeBill(groceries)

给出输出:

10.0
43.5
45.5

如果您只想打印出总数,那就是没有 return 语句。

于 2013-02-05T17:17:43.440 回答
0

只是另一种解决方案。

groceries = ["banana", "orange", "apple"]
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}

print(sum(stock[item] * prices[item] for item in groceries))
于 2013-02-05T19:05:21.573 回答