Home > Back-end >  Python change "globalish" variable inside a function
Python change "globalish" variable inside a function

Time:06-21

The following code

def myfunc():
  x = ""
  print("Python is "   x)
  def hi():
    global x
    x = "OMG"
  hi()
  print("Python is "   x)
    
myfunc()

just prints "Python is" twice. I was expecting that the second print-statement prints "Python is OMG".

Does some one has an idea how to accomplish that? I could just declare x as a global variable, but I would like avoid it, because a constraint of my programming task is to only change code inside the myfunc-Function.

CodePudding user response:

"Globalish" is spelled nonlocal :)

The x you want to modify inside hi is not a global variable, but a local variable in the enclosing scope, so you use the nonlocal keyword to specify the variable named x in the closest enclosing scope with such a variable.

def hi():
    nonlocal x
    x = "OMG"
  • Related