I am following 6.00.1x from MITx and the slide (as attached below) confuses me. Specifically, why does h(y)
comes back as unbound local error.
The following is a further explanation posted:
n += y
, which is the same asn = n + y
, will fail ifn
hasn't been defined locally or already declared nonlocal or global because
- the interpreter first evaluates the right side of the
=
so findsn
in the global scope (& thus readable) and addsy
to that, then- the interpreter tries to bind the result of global
n + y
ton
on the left of the=
. But becausen
isn't local & hasn't been declared global this attempted binding creates the error.
The first bullet point is straightforward. In the second one, I understand that the interpreter is trying to bind the result of n + y
to n
. n
is not local and that's fine; but it has been declared in the global scope hasn't it? Specifically, x=5
declared the variable.
The issue here seems to be that the function is trying to bind n
(or in this case x
) to the global scope, but that is not allowed - I understand that binding results from local scope to global is not allowed, but doesn't Python instantiate n
/x
in the local scope automatically and bind n+y
to that instead?