Python callback function is an advanced tip for python programmers, which is very useful for streamlineding our code and application structure. In this tutorial, we will introduce how to use it.

**What is python callback function?**

General speaking, python callback function is a function that can accept other functions as parameters.

Here we will use an example to help you understanding it.

**Preliminaries**

We create a function to compute ** 2*x**.

def compute(x): return x*2

**Create another function to accept a function name as parameter.**

def listnum(x,f): return x + f(x)

In function ** listnum(x, f) **,

*parameter is a function name.*

**f****can accepte a function as its parameter.**

*listnum***Test python callback function**

for i in range(10): x = 0 if i % 2 == 0: x = listnum(i, compute) else: x = i print(x)

In this test code, we can find that function ** compute** is passed into

**as a parameter. Then you can get a result like:**

*listnum*0 1 6 3 12 5 18 7 24 9

To use python callback function, you must notice parameters of function which is called.

For example:

def listnum(x,f): return x + f(x)

In** listnum** function,

**is a function which is called in**

*f(x)***function, which means that if a function (**

*listnum***) can be used as a parameter of**

*f***, it must accept one parameter**

*listnum***. Otherwhile, it will not be used as a parameter of**

*x***.**

*listnum*For example:

def computeXY(x, y): return x+y def listnum(x,f): return x + f(x) for i in range(10): x = 0 if i % 2 == 0: x = listnum(i, computeXY) else: x = i print(x)

In this code, ** computeXY** accept two parameters, however, there only one parameter in

**, which is in**

*f(x)***.**

*listnum(x, f)*So you will get error:

File "e:\workspace-python\Y-MK\open-url.py", line 11, in listnum return x + f(x) TypeError: computeXY() missing 1 required positional argument: 'y'