I recently came across the idea of defining a function within a function in Python. I have this code and it gives this error:
def f1(a):
def f2(x):
return a+x
return 2*a
Error: On calling f2(5)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
f2(5)
NameError: name 'f2' is not defined
I am having some difficulty understanding the way global variables are used across functions or even in recursive calls. I would really appreciate it if someone would point out my mistake and maybe help me along the way. Thanks!!
You defined
f2in the local namespace off1only; it is not available globally.If you want such a nested function to be available at the module level, you’d have to either return it from the function, or define a
globalvariable to store it in:then call that as
result, f2 = f1(somevariable_or_literal).The
globalapproach is not recommendable (using aglobalrarely is) but would look something like:at which point
f2will be set when you have calledf1.