Something of Value


A Day at the Supermarket

Why does the code not print the total? It seems to work when I set 'total' = 0 before the loop starts, but why doesn't it work when done inside the loop?

Replace this line with your code. 
for fruit in prices:
    total = 0 
    net = prices[fruit] * stock[fruit]
    print net
    total = total + net
print total


consider this line of code

for fruit in prices:
    total = 0

As you set total=0 inside the loop every time you add 0 to net.At the last line of the loop you change the total but again you set total=0 so you start from 0.

but if you set total=0 before the loop then it starts from the last value you added.

print the total inside the loop you can see the difference.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.