3

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.

milanbalazs
  • 4,811
  • 4
  • 23
  • 45
Sol
  • 33
  • 3
  • https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops – Joe Aug 14 '19 at 07:16
  • This is actually a good question. It describes the situation, has working, minimal sample code, discusses the reasoning and states the expectation. – Tomalak Aug 14 '19 at 07:25

1 Answers1

3

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

Ron Serruya
  • 3,988
  • 1
  • 16
  • 26
  • That makes sense. So if the loop was a function instead, then the total would stay as zero? – Sol Aug 14 '19 at 07:20
  • Correct, unless you used the "global" keyword, to refer to the `total` var from outside the function. Check this out https://www.programiz.com/python-programming/global-local-nonlocal-variables – Ron Serruya Aug 14 '19 at 07:22
  • 4
    btw, I see that you are using python 2, I recommend you move to python 3 as early as possible. Python 2 is 9 years old and will be non-supported in a year – Ron Serruya Aug 14 '19 at 07:23
  • 2
    Wow very useful link. Thank you for the answer and advice. ill definitely move to python 3 asap! – Sol Aug 14 '19 at 07:28