0

I would like to access a variable that is computed in a function but which is not the return value. I am calling this function in another function so I cannot change the return value (I know this is what people usually suggest doing). I have tried using global in front of my variable but when I call it outside, I have the following error: NameError: global name 'DA' is not defined My code looks like this:

 def function():

     global DA

     DA = something

     ....

 return something_different

print DA #(outside the function)

I am relatively new to Python so maybe there is something obvious that I am missing here. Thanks!

Sasha
  • 101
  • 2
  • possible dupe of [Using global variables in a function other than the one that created them](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – chickity china chinese chicken Jan 24 '17 at 23:56
  • Did you actually _call_ `function`? The code within a function is only executed when the function is called, if you just define the function and don't call it, it won't assign any value to the global `DA`. – ShadowRanger Jan 25 '17 at 00:08
  • thanks for your answer. what I am confused about it that if I call function() then won't it give me the return value and not DA ? – Sasha Jan 25 '17 at 01:25

2 Answers2

0

You have to first define DA outside of the function. global does not create a new variable and insert it into the global scope. The global keyword tells the function to refer to the existing definition of DA instead of creating a new variable with the same name local to the function. This is in opposition to the default, which is to have any variable assigned (with an equals sign) within a function be local to the function and locally override the definition of any variable of global scope with the same name, with the original definition restored outside of the function's scope.

BallpointBen
  • 9,406
  • 1
  • 32
  • 62
  • You don't need to define `DA` outside the function, but if the only definition is within the function, you have to actually _call_ the function (and it must traverse a code path that defines the `global` in question) so the assignment occurs. – ShadowRanger Jan 25 '17 at 00:07
-1

return DA ****program****

def function():

     global DA

     DA = something

     ....

 return DA

print(DA) #(outside the function)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Neeraj
  • 1