1

Right, so I'm making a program...

def aFunction():
    aVariable = 5

aVariable = 9
aFunction()

...and of course this won't work. What I am trying to do is to make aVariable changeable in other functions, namely, aFunction. How do I do that? Can I use the global statement, I have heard some bad things about it, although I don't really remember why?

PhP
  • 82
  • 7

2 Answers2

2

You should use global:

def aFunction():
    global aVariable
    aVariable = 5

aVariable = 9
aFunction()
print aVariable #print 5
NorthCat
  • 9,643
  • 16
  • 47
  • 50
  • its important to note this is only required if you are changing the variable ... you have read access to it always ... that said its probably best to avoid in general (+1 all the same) – Joran Beasley May 15 '14 at 19:04
2

So this is a comprehensive explanation why global variables are bad in every programming language: global variables are bad

For your problem, you can use return values, for example:

def a_function(a_variable):
    return a_variable - 5

a_variable = 9
a_variable = a_function(a_variable)
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • a_function doesn't take in parameters.... – Quintec May 15 '14 at 19:05
  • you can read globals easily but it should just take it as an argument or encapsulate it in a class ... basically I concure very much with this answer – Joran Beasley May 15 '14 at 19:05
  • Well, I kind of know I could use that. But I'd rather not have to call aFunction with aVariable as a parameter as every time aFunction is called I don't need aVariable... If that makes sense. Also, I'd rather not have to pass around aVariable to all functions where it could possibly be needed. – PhP May 16 '14 at 19:52