[Tutor] Basic Question

Mats Wichmann mats at wichmann.us
Thu Sep 9 18:46:05 EDT 2021


On 9/9/21 3:58 PM, Osmaan Mysorewala wrote:

> A followup question for Mr. Wichmann, I've heard that global variables 
> are not great, and I see that you wrote some pseduocode on how to fix 
> it. Still I don't really understand how to implement that in my code. 
> Everytime I tried using local variables to store the arrays, it gave the 
> error "local variable referenced before assignment". If possible, do you 
> think you could go into a bit more depth on how it would work?

So this is another one of the things that trips up newcomers to Python, 
and that's what's called scope.  It seems like this particular problem 
was loaded with traps, I wonder if maybe it came too early in whatever 
course (or tutorial, or whatever) you're on?  Well, no matter.

Global variables in Python aren't really global, they're module-global. 
That's a distinction that may not make much sense at this point.  It 
just means they're available everywhere in the particular Python file 
they're declared in, but if your program has other modules that are 
imported those wouldn't have access to this so-called global.  Enough of 
that...

Python has a kind of interesting approach to what is global and what is 
local.  I'm sure this will be covered in your material eventually so 
just quite briefly: if you write a function that just accesses a 
variable declared not in the function, but at the module level, then 
that "just works".  If you try to change it, then that variable is 
considered local to the module instead, *unless* you list it as global. 
Being local means you can't access it before you set it. It's maybe 
easier to show this in an interactive session than to try for words (I 
added some comments with a # comment mark).  Don't worry, this will 
definitely come up in any course, so don't need to worry about it just 
now, just know that you're not nuts :)

 >>> FOO = 100   # this is a (module) global...
 >>> def myfunc():
...     print(FOO)
...
...
 >>> myfunc()
100  # access to global in func is fine
 >>> print(FOO)
100  # as it is at module level
 >>> def myfunc():
...     FOO = 50
...     print(FOO)
...
 >>> myfunc()
50  # FOO was local to myfunc
 >>> print(FOO)
100  # didn't change the global one
 >>> def myfunc():
...     print(FOO)
...     FOO = 50
...
 >>> myfunc()
Traceback (most recent call last):
   File "<input>", line 1, in <module>
     myfunc()
   File "<input>", line 2, in myfunc
     print(FOO)
UnboundLocalError: local variable 'FOO' referenced before assignment
# because function would write to it, it's not global
# thus the print before the assignment is an error
 >>> def myfunc():
...     global FOO
...     print(FOO)
...     FOO = 50
...
 >>> myfunc()
100  # declared "global", so we're printing the global one
 >>> print(FOO)
50   # and myfunc changed the global one, since it was declared "global"
 >>>



More information about the Tutor mailing list