How to return function from function in Python

3 Answers

0 votes
def function1():
    print('function1()')
    return function2

def function2():
    print('function2()')

f = function1()
f()



'''
run:

function1()
function2()

'''

 



answered Jan 9, 2021 by avibootz
0 votes
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def calc(operation):
    if operation == 1:
        return add
    elif operation == 2:
        return subtract
    elif operation == 3:
        return multiply


func = calc(1)
print(func(4, 5))

func = calc(2)
print(func(4, 5))

func = calc(3)
print(func(4, 5))



'''
run:

9
-1
20

'''

 



answered Jan 9, 2021 by avibootz
0 votes
def f(a):
    print("f() a =", a)
 
    def test(b):
        print("test() a =", a)
        print("test() b =", b)
        return a + b
     
    return test
 
f1 = f(1)
f2 = f(2)
print("------------")
 
print(f1(4))
print(f2(5))
 
 
'''
run:
 
f() a = 1
f() a = 2
------------
test() a = 1
test() b = 4
5
test() a = 2
test() b = 5
7
 
'''

 



answered Apr 23, 2024 by avibootz

Related questions

2 answers 132 views
2 answers 147 views
1 answer 129 views
1 answer 138 views
3 answers 219 views
1 answer 161 views
3 answers 251 views
...