Skip to content

Python call function from another function

  • by

You can call many functions from another function in Python. Each of the functions we write can be used and called from other functions we write.

# function definition
def fun():
    print("Called fun()")


# calling a function
fun()

You can do something like this:

def addOne(x):
    return x+1

def useFunction(addOne, x):
    return addOne(x)**2

Python call function from another function

Simple example code.

def fun2():
    print("Called by fun1()")


def fun1():
    print("Called by main function")
    fun2()  # calling fun2() from fun1()


fun1()

Output:

Python call function from another function

Use a function Output as an Input of another function

# Method 1: using return value inside another function

def fun1(a):
    res = a + 1
    return res


def fun2(c):
    res = c * 2
    return res


output = fun1(fun2(1))
print(output)


# Method 2: directly calling one function in the other
def function_1(n):
    v = n * n
    num = function_2(v)
    return num


def function_2(a_number):
    a_number = a_number * 2
    return a_number


print(function_1(10))

Output:

3
200

Call a nested function (function inside another function)

Create a nested function attribute like so:

def foo():
    # for closures or strictly local function
    # then this is useful!
    # ugly hack other wise to try and create methods.
    def bar():
        print('bar')    
    
    # if there are multiple function, return a container...
    return bar

Then:

foo.bar=foo()
foo.bar()
# prints 'bar'

But, this is far easier with a class:

class Foo:
    # class can hold related methods, setters and getters, 
    # protected variables, etc. 
    # Python is DESIGNED to do this.
    def bar(self):
        print('bar')

Then:

f=Foo()
f.bar()
# prints 'bar'

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *