⊗pyPmFnCa 10 of 128 menu

Callback functions in Python

Python has the ability to pass functions as parameters to other functions. In this case, the functions are passed as variables (without parentheses) and are called callbacks. Such callback functions will be executed in the body of the main function.

Let us have a function test, which takes a number and a function as parameters:

def test(num, func): pass

Now let's create a function func that will raise a number to a square power:

def func(num): return num ** 2

Now let's go back to test and add code to its body so that the callback function passed as a parameter also accepts a number as a parameter. As a result, the result of test will be the operation of another function, the number for which will be taken from the first parameter of test:

def test(num, func): print(func(num))

Next, we call the function test and pass it 3 as the first parameter, and func as the second:

test(3, func) # 9

What will be the result of running the following code:

def get_Info(txt, func): print(func(txt)) def func(name): return 'user name is ' + name get_Info('john', func)
enru