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

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()



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

# 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




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():
    # if there are multiple function, return a container...
    return 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):


# 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading