Calling functions in a loop

Bill Bell bill-bell at bill-bell.hamilton.on.ca
Sat Jul 14 22:32:19 CEST 2001


With

>>> def fn1 ( ):
... 	print "fn1"
... 	

and

>>> def fn2 ( ):
... 	print "fn2"
... 	

Use

>>> x = [ fn1, fn2 ]
>>> for f in x:
... 	f()
... 
fn1
fn2

or

>>> y = ['fn1', 'fn2']
>>> for f in y:
... 	eval ( f ) ( )
... 	
fn1
fn2

> n_d_gangadhar at yahoo.com (NANDYALA D Gangadhar)
> 
> Hello,
> 
> I am new to Python (I already like it very much) and I have a newbee
> question: How do I call a set of functions from inside a loop? I tried
> the following, and it understanbly fails with:
> 
> TypeError: object is not callable: 'Fn1'
> 
> -- Code --
> #!/usr/bin/env python
> 
> __all__ = ["Fn1", "Fn2"]
> 
> def Fn1():
>         print "I am Fn1"
> 
> def Fn2():
>         print "I am Fn2"
> 
> if __name__ == "__main__":
>         for Fn in __all__:
>                 Fn()    
> -- /Code --
> 
> Would someone show the correct way of getting the functionality I
> need?






More information about the Python-list mailing list