-1

I want to use some variables through the code, of course if the variable is global, it's ok. But I want to use functions, so I could just pass some parameters in my future work.

For example, this code is throwing an error:

def fun1():
  print a_variable

def fun2(a_variable='hello, world'):
  fun1()

fun2('hello, world')

Error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-42-31e8e239671e> in <module>()
      5   fun1()
      6 
----> 7 fun2('hello, world')

<ipython-input-42-31e8e239671e> in fun2(a_variable)
      3 
      4 def fun2(a_variable='hello, world'):
----> 5   fun1()
      6 
      7 fun2('hello, world')

<ipython-input-42-31e8e239671e> in fun1()
      1 def fun1():
----> 2   print a_variable
      3 
      4 def fun2(a_variable='hello, world'):
      5   fun1()

NameError: global name 'a_variable' is not defined

Since a_variable is valid in fun2, how come fun1 is not? How can I resolve this? I don't want to add additional parameters to fun1.

insomnia
  • 191
  • 2
  • 12
  • Possible duplicate of [Using global variables in a function other than the one that created them](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) –  Mar 29 '18 at 07:24

1 Answers1

1

In python there's a simple statement to make variables global. However, first you need to change the name of the variable in your parameter-list of fun2(). After this change you can insert the global-statement:

def fun2(a='hello, world'):
    global a_variable # declaration
    a_variable = a # definition
    fun1()

If you don't change the parameter-list you get another error: 'a_variable' is local and global.

Aemyl
  • 1,501
  • 1
  • 19
  • 34
  • Hi, thanks. This works. But I don't really like this. Because this bring a global variable but in fact 'a_variable' just need to be "global" in the namespace of "fun2". – insomnia Nov 03 '16 at 13:33
  • maybe you should put the line `global a_variable` outside of any function (but still before the first function call). Then you don't need to call `fun2` to make the variable global. – Aemyl Nov 03 '16 at 13:40
  • ok, `global a_variable` outside a function doesn't do anything in this case. it probably doesn't work because inside the `fun2`- function the variable is interpreted as local, as long as you don't explicity tell the interpreter to refer it to the global variable. In other words: you probably need the `global a_variable` statement inside `fun2()`. – Aemyl Nov 03 '16 at 15:48