Search code examples
pythonpython-3.xfunctionnameerror

Error in defining a function that defines another function


(Note:-You can just scroll into the bold parts for the main information.)
Thank you for investing your time in answering my question. I have a python-3 error in defining a function that defines another function with the following code:

def one():
    def two():
        print("two()")
one()
two()

And error:

Traceback (most recent call last):
  File "C:\Users\homec\AppData\Local\Programs\Python\Python39\test.py", line 60, in <module>
    two()
NameError: name 'two' is not defined

After defining one(), I called one() so I defined two(). Then I called two() so I printed "two()". Then what is the problem here, why is it saying name 'two' is not defined.
Thanks in advance for answering.


Solution

  • The function two just isn't available at the outer/global scope.

    See this example on how to define it at the global scope:

    In [7]: def one():
        ...:     global two
        ...:     def two():
        ...:         print("two()")
        ...: one()
        ...: two()
    two()