Aug-06-2018, 07:42 PM
There are three different
If
...and that's why you avoid having variables with the same name. It adds unneeded confusion. It's highly unlikely that all three of those refer to the same thing, which means they're all poor choices for a variable name, as none actually describe what a
spam
variables. A local spam, within do_local()
, a local spam, within scope_test()
(which is non-local for enclosed functions), and a global spam, which doesn't exist until after do_global()
is called. do_global()
creates a new variable in the global scope, but it doesn't change any of the other spam
s that already exist in other scopes. After do_global()
is called, referencing spam
uses the local version, which is set to "nonlocal spam"
at that time.If
print(spam)
were to return "global spam"
, that would violate scoping, as there's a local spam that exists....and that's why you avoid having variables with the same name. It adds unneeded confusion. It's highly unlikely that all three of those refer to the same thing, which means they're all poor choices for a variable name, as none actually describe what a
spam
is.