[Tutor] Local/Global Variable

Alan Gauld alan.gauld at blueyonder.co.uk
Tue Jun 15 02:38:04 EDT 2004


> It is my understanding that if python does not find a variable
locally, it is
> coded to look for it globally.

Correct, where globally means in the same file but outside any
class or functionn definitions.

> defined the variable outside of the loop in the outermost area of
code. Short of
> inserting 'global variablename' in every loop, is there any way to
remedy this?
> Relevant segment(s) of code:

You only need to put the global declaration in the function not in
each loop.

Thus in your sample you could put the global statement as the
first statement inside the function.

> def convertnum():
      global res
>     if whichconv in('1','Binary','binary','Bin','bin','B','b'):
>         if int(original) <= 0:
etc...

>             for char in original:
>                 if char in punct:
>                     res += char

Note that if you had not been assigning a value to res you would
not need the global statement, but because you are trying to assign
to it PYthon is attempting to create a local variable called res.
But because the value of res relies on res (effectively you are
saying

res = res + 1

which Python cannot compute)

> UnboundLocalError: local variable 'res' referenced before assignment

Which is why the error is phrased the way it is.

Python makes use of global variables slightly awkward for the very
good reason that global variables are bad pratice, so you have to
have a good reason for using them. In most cases where you might
try to use a global it is better to pass a parameter in or return
a value. Python ties quite hard to encourage good programming
habits while not preventing you from avoiding them if you really
need to.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list