Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I am running a function within another function. However, the more nested function is unable to access the variables in the main, more global function. When I attempt to run my code I get "x is not defined" error. I would think that since x is a more global variable higher in scope, it should be accessible.

def func_master():

    x = 'hello world'

    test_sub()

def test_sub():

    print(x)

func_master()

I want it to print out 'hello world'.

1 Answer

0 votes
by (25.1k points)

Your functions are not "nested," which means that one is defined inside the other. You instead are calling one function from inside another, but the functions are defined separately, neither inside the other.

Python's scope rules are based on how the functions are defined. So when func_master calls test_sub, the name x that was defined in func_master is not accessible to test_sub.

The best (but not only) way to make x usable in test_sub is to pass it as a parameter. Modify the call in func_master to pass x and modify the definition of test_sub to receive it. It is good programming practice for one routine to pass all the needed information as parameters--avoid using global variables etc. unless they are absolutely needed.

def func_master():

    x = 'hello world'

    test_sub(x)

def test_sub(x):

    print(x)

func_master()

Browse Categories

...