A day at the supermarket (9/13) - something of value

my initial code :

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

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

for fruit in prices:
print fruit
print "price: " + str(prices[fruit])
print "stock: " + str(stock[fruit])
print

for fruit in prices:
total = 0
total =total + prices[fruit] * stock[fruit]

print total

this returned the value of total as 0.

however, when i did this -

total = 0
for fruit in prices:
total =total + prices[fruit] * stock[fruit]

print total

it worked properly.
why does this happen?

Because the variable is initialized before the loop. In the earlier example it is zeroed out inside the loop, so cannot accumulate.

1 Like