In Python, functions can be passed as arguments to other functions. This is known as higher-order functions, and it allows for a powerful and flexible programming paradigm. Here's an example:
def add(x, y): return x + ydef do_twice(func, x, y): return func(func(x, y), func(x, y))print(do_twice(add, 2, 3)) |
In this example, we define two functions add and do_twice. The add function takes two arguments and returns their sum. The do_twice function takes a function func and two arguments x and y, and calls func twice with the arguments x and y.
We then call do_twice with the add function and the arguments 2 and 3. The result is 20 because add(add(2,3), add(2,3)) evaluates to add(5,5) which is 10.
This is just one example of how functions can be used as arguments in Python. By passing functions as arguments, we can write more flexible and reusable code.