I have 2 sets of code that I thought would have the same outcome, and I was wondering why they both wouldn't accomplish the same output in the console. Specifically, I can't figure out why the 2nd set of code is giving me a 0 rather than the cumulative total.
1. EDITOR prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
total = 0 for food in prices: print prices[food] * stock[food] total = total prices[food] * stock[food] print total
CONSOLE 48.0 45 24 0 117.0
2. EDITOR prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
total = 0 for food in prices: total = prices[food] * stock[food] print total total = total prices[food] * stock[food] print total
CONSOLE 48.0 45 24 0 0
CodePudding user response:
your code is unreadable , please determine the statements & their scope
CodePudding user response:
When you iterate over the dictionary (the line that reads for food in prices
) you get the dictionary keys as an iterator, which means that on each call of the loop the variable food becomes each of the keys in turn. In this case, the first loop it has the value orange
, then pear
, then banana
, then apple
(I worked this out from the console output). N.B. that (I guess you're using Python 2.7 or at least before 3.6, when dictionaries became ordered) the order of iteration for the dictionary is different to the order you wrote them; that's normal behaviour for old Python.
Then, as to why you are getting unexpected results: in the first case, on each iteration you update total
, which starts at 0, with the value you are printing out. So, total gets bigger every time, and persists between iterations of the loop.
On the other hand, in the second example you reset total each time with the line total = prices[food] * stock[food]
. This means that total doesn't keep the information from the previous iterations. Then, because the final food
, apple
, is out of stock (stock[apple] = 0
) total
gets set to 0 at the start of the loop, and then only 0 is added to it. So, it makes perfect sense that the final value of total is 0 :)
I hope that helps!
CodePudding user response:
In case 2, you are overwriting the total again and again, and because of that, you are getting different output. Replace total with another variable (for example, tmp). Please follow the code below.
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
total=0
for food in prices:
print(prices[food] * stock[food])
total = total prices[food] * stock[food]
print(total)
print('________2nd for loop_______________')
total=0
for food in prices:
tmp = prices[food] * stock[food] #you are over writing total every time replace it with another variable (tmp)
print(tmp)
total = total prices[food] * stock[food]
print(total)