1

I have a simple python code as follows:

def outer():
    x = None
    y = None
    z = None

    def set():
        x = 1
        y = "Y"
        z = 2

    def get():
        return x, y, z

    set()
    m, s, n = get()
    print("%s, %s, %s" % (m, s, n))


outer()

I would like to get 1 Y 2, but the result is None None None.

It looks that the variable x,y,z is not set by the set method,

I would ask how to get the result 1 Y 2

Tom
  • 5,848
  • 12
  • 44
  • 104

1 Answers1

1

You can do it using the nonlocal keyword.

def outer():
    x = None
    y = None
    z = None

    def set():
        nonlocal x
        nonlocal y
        nonlocal z
        x = 1
        y = "Y"
        z = 2

    def get():
        return x, y, z

    set()
    m, s, n = get()
    print("%s, %s, %s" % (m, s, n))


outer()

You can access global variables using the global keyword.

Rohan Mukherjee
  • 280
  • 2
  • 7