What happens if I don't initialize my variable? : Keeping Track of the Produce



I've been playing about with my code in this exercise to try and work out why it's necessary to initialize the variable 'total = 0' before the 'for' loop.
When I change 0 to 10, the output predictably increases by 10.
But when I remove the 'total = 0' altogether, the code still runs, but ends up doubling the final figure.

My question is; why does this happen? I can't understand any logic.

I've been guided to the link below, but can't make head or tail of if. Can anyone explain in simple terms?


this effect must be caused by your browser sending cached data, try to make a python script on your computer, see what happens

it should give syntax errors.


Good answer. Thank you. When I run the code without 'total = 0' I get the following error in terminal, which makes sense.

Thanks again!

Traceback (most recent call last):
File "/var/folders/w8/g1hpq38j68g5f_69l4mx3l440000gn/T/com.weirdrocketeer.Foobar/B0066FD9-6D84-45DF-B
F4C-0996D755933C/index.py", line 22, in
total = total + (prices[key] * stock[key])
NameError: name 'total' is not defined