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!!
If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.
A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope.
Calling a function from within itself is called recursion and the simple answer is, yes.
In Python, it is possible to pass a function as a argument to another function. Write a function useFunction(func, num) that takes in a function and a number as arguments. The useFunction should produce the output shown in the examples given below.
f2
is defined inside f1
. Therefore, it's scope only extends inside the function f1
. Outside of that space, the function f2
doesn't even exist, which is why you're getting the error.
If you were to call f2
from somewhere inside f1
after f2
is defined, it would work.
Short Description of Python Scoping Rules has a good explanation of how scope works in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With