Mouad Maaziz
Mouad Maaziz

Reputation: 21

access python global variable in a nested function

I' am a beginner in python language. I've got a headache in understanding how global variables work. this is a specific example that doesn't make sense to me:

def func():
    def nested():
        global x
        x=1
    print(x)

func()

this throws :global name 'x' is not defined

Why is x is not available even though it has been made global in the nested function?

Upvotes: 1

Views: 132

Answers (1)

Javad Rezaei
Javad Rezaei

Reputation: 1110

you have to call nested() to define global variable x. ithout calling it, there is no definition of variable x and so you will have error!

def func():
    def nested():
        global x
        x=1
    nested()
    print(x)

func()

Upvotes: 3

Related Questions