[Tutor] Passing functions(with parameters) as paramiters to (looping)functions.

Jeff Peters jeffp at swva.net
Tue Aug 16 18:44:41 CEST 2011


Hi;

I am trying to run a function inside a continuing loop, but do not seem 
to be able to pass any parameters (arguments ) when I do so.
I have placed working and non-working code , with output below.

## This works:

def loop(fn ):
     for i in range(5):
         fn(  )

def this_function(a=" i am not a string"):
     print( a )

loop(this_function)

## with output:
 >>>
  i am not a string
  i am not a string
  i am not a string
  i am not a string
  i am not a string
 >>>

## But , this does not :

def loop(fn ):
     for i in range(5):
         fn(  )

def this_function(a=" i am not a string"):
     print( a )

loop(this_function("I am a string") )  ## note the only change is here

## With this as output:

 >>>
I am a string
Traceback (most recent call last):
   File "/home/jeff/MyPythonStuff/call_sub.py", line 9, in <module>
     loop(this_function("I am a string") )
   File "/home/jeff/MyPythonStuff/call_sub.py", line 4, in loop
     fn(  )
TypeError: 'NoneType' object is not callable
 >>>

My OS is Debian  64 bit
I get the same output for both python2.7 and Python3.1
I think this should be do-able but I am in need of a clue.
Thanks.









More information about the Tutor mailing list