3 ms·
Good point. I think serious python people (not me, I had to search a bit) would understand the scoping well enough to recognise the gotcha. Turns out the probl
by rm445 12y ago
Good point. I think serious python people (not me, I had to search a bit) would understand the scoping well enough to recognise the gotcha.
Turns out the problem is the +=, perhaps it would be a bit clearer if written as:
grand_total = grand_total + to_add
which introduces a new local variable called grand_total shadowing the outer one. So it's straightforward enough, the pitfall is missing the shadowing.
Note that you could use the outer grand_total without problems if you don't shadow it, e.g. using it as an rvalue (is that a pythonic term?) , and also note Python 3 provides a 'nonlocal' keyword to let you pull the outer variable into scope so it won't be shadowed.