How do I make a variable created inside a function global?

I have a function in a program that I am working on and I named a variable inside that 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 undefined.

Any help would be great, thanks.

+3


source to share


3 answers


I've made some changes to your function.

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

      

Now if you do



print (a)

      

deduces

1

      

+2


source


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

First of all, you should be careful about using any global variable as it might be considered bad practice to do so . Making a global from a function is even worse. This will make the code extremely unreadable and difficult to understand. Imagine reading code that uses random a

. First you need to find where this thing was created and then try to figure out what happens to it during program execution. If the code isn't small, you are doomed.



So, the answer to your question is just use global a

before assignment, but don't follow.

BTW. If you want a C ++ static variable like a function check this question.

+2


source


First, it is important to ask "why" is it needed? Basically, the function returns "local computation" (usually). That being said, if I need to use the return 'value' of a function in the "global scope", it's easier to just "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)

      

However, it is important to ask “why” I would like to do this, usually?

+1


source







All Articles