1

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?

3
  • It's not really the global. x is only defined in a function you never call, but you try to print it. Try calling nested() before printing and the global will get defined. Commented Jul 12, 2020 at 23:03
  • yes. Because it isn't defined. Why do you expect it to be defined? nested is never called anywhere. Commented Jul 12, 2020 at 23:03
  • 1
    @MarkMeyer thank you. the global x inside a function won't define a variable outside unless it's called. I get it now. Commented Jul 12, 2020 at 23:09

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.