Reputation: 33
Just to be clear, I am an absolute beginner and I am self teaching myself python. So if this question is obvious idk. Also if you could recommend me stuff to learn python logic I would appreciate that.
So, the variable is named total and is equal to zero. When I print the total after the loop, the total changes to 117.
why when I call the total after the loop it changes? Shouldn't it stay the same because its not inside the loop?
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
I expected the total to stay equal to 0.
Upvotes: 3
Views: 68
Reputation: 4426
Loops are not their own scope, so total inside the loop is the same total outside of it, you can see it by printing id(total) in and out the loop, and see that its the same one
Upvotes: 3