Can you pass functions as arguments?

Paul Rubin http
Mon Dec 19 02:18:48 EST 2005


bobueland at yahoo.com writes:
> I want to calculate f(0) + f(1) + ...+ f(100) over some function f
> which I can change. So I would like to create a function taking f as
> argument giving back the sum. How do you do that in Python?

You can just pass f as an argument.  The following is not the most
concise or general way, it just shows how you can pass a function.

    def square(x): 
       return x**2

    def sum100(f):    # f(0)+f(1)+...+f(100)
       s = 0
       for i in xrange(101):
          s += f(i)
       return s

    print sum100(square)    # pass square as an argument



More information about the Python-list mailing list