3

I have a function in a program that I`m working at and I named a variable inside this function and I wanted to make it global. For example:

def test():
   a = 1
   return a

test()

print (a)

And I just can`t access "a" because it keeps saying that a is not defined.

Any help would be great, thanks.

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
Nicolas Fonteyne
  • 164
  • 3
  • 13
  • 1
    Are you working in python? Hard to tell without a tag. If so, [this answer](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) might be helpful. – fzzfzzfzz May 23 '15 at 03:39
  • 4
    What language is this for? If you cannot comment yet, please add the tag to your question. – Drakes May 23 '15 at 03:39
  • 3
    [Don't forget to ask a search engine before asking us.](https://www.google.com/search?q=python+global+variable) Unlike humans, Google doesn't get tired of people asking it the same question over and over. – user2357112 May 23 '15 at 04:39
  • As many people have already mentioned, global variables are pure evil. Stick to the paradigm of functional programming, i.e. functions should have no side effects on the outer scope. – Eli Korvigo May 23 '15 at 04:46

3 Answers3

3

I have made some changes in your function.

def test():
    # Here I'm making a variable as Global
    global a
    a = 1
    return a

Now if you do

print (a)

it outputs

1
Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
2

As Vaibhav Mule answered, you can create a global variable inside a function but the question is why would you?

First of all, you should be careful with using any kind of global variable, as it might be considered as a bad practice for this. Creating a global from a function is even worse. It will make the code extremely unreadable and hard to understand. Imagine, you are reading the code where some random a is used. You first have to find where that thing was created, and then try to find out what happens to it during the program execution. If the code is not small, you will be doomed.

So the answer is to your question is simply use global a before assignment but you shouldn't.

BTW, If you want c++'s static variable like feature, check this question out.

Community
  • 1
  • 1
khajvah
  • 4,889
  • 9
  • 41
  • 63
1

First, it is important to ask 'why' would one want that? Essentially what a function returns is a 'local computation' (normally). Having said so - if I have to use return 'value' of a function in a 'global scope', it's simply easier to 'assign it to a global variable. For example in your case

def test():
    a = 1    # valid this 'a' is local 
    return a

a = test() # valid this 'a' is global
print(a)

Still, it's important to ask 'why' would I want to do that, normally?

gabhijit
  • 3,345
  • 2
  • 23
  • 36