Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function within a function in python

Tags:

python

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!!

like image 332
OneMoreError Avatar asked Nov 03 '12 13:11

OneMoreError


People also ask

Can you use a function within a function Python?

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.

How do you access a function within a function Python?

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.

Can you use a function within a function?

Calling a function from within itself is called recursion and the simple answer is, yes.

How do you define a function within another function in Python?

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.


1 Answers

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.

like image 123
Collin Avatar answered Oct 26 '22 03:10

Collin