Question about global statement...

Can somebody point me out how the global statement is used in python ? Is ti only nescesery when i want to assign a value to a global variable inside a function ?


let’s say that if i have the following code :



def x ():
print y




def x();
global y
print y


is the global statement needed only in the second code in order to assign the value ?

Global gives you access to define where variables can be used.

For instance, if you declare a variable to be global inside of a function, then you can then use the value associated with that variable outside of that function. Similarly if you have a variable and you declare its access to be global, then when you assign into it in a function it will change the global value, otherwise it will change only the value designated to the namespace of the function.

For instance

y = 5

def f():
     y = 30
     print y #print 30

def fb():
     global y
     y = 50

print y #prints 50, back in global namespace

def fa():
     global z
     z = 20
print z #prints 20

I suggest playing around with it to get it to work properly, but keep in mind that python will resolve name issues from the most interior namespace outward. If there is a global variable var and a local variable var, then the local variable will take precedence over the global variable. If you reference var inside of a function, and there is no local var, python will start looking in the global namespace (or next highest namespace) for var. This is why its good programming practice to adopt a different naming scheme for local and global variables. In general I do the following:

  • Local variable: var or varFoo or varFooBar (you get the idea)
  • Global variable: VARIABLE (all caps)I tend to avoid the same names (even across caps), just to be safe, although python is case sensitive in variable names. I’m not the greatest at namespace stuff like this, but this is how I understand it from the functionality aspects I employ, so there are likely some little nitpicky things I missed, but take it as you will, or somebody will come fix me…