Differences between revisions 1 and 2
Revision 1 as of 2008-04-13 17:23:47
Size: 412
Editor: anonymous
Comment:
Revision 2 as of 2008-04-14 09:43:52
Size: 1527
Editor: anonymous
Comment:
Deletions are marked like this. Additions are marked like this.
Line 8: Line 8:
Functions can be passed as arguments to functions == Function with one argument ==
{{{
In [124]: def quadrat(x):
   .....: return x**2
   .....:

In [125]: quadrat(2)
Out[125]: 4
}}}

== Function with variable number of arguments ==
{{{
In [126]: def printargs(*args):
   .....: for arg in args:
   .....: print arg
   .....:

In [127]: printargs(a)
[1, 2, 3]

In [128]: printargs(a,range(4))
[1, 2, 3]
[0, 1, 2, 3]
}}}
== Function with variable number of keywords ==

{{{
In [131]: def printkeys(**kw):
   .....: for k in kw.keys():
   .....: print k,kw[k]
   .....:

In [132]: printkeys(key1=10,key2='Hallo')
key2 Hallo
key1 10
}}}


== Function with functions as arguments ==

Functions can be passed to functions as arguments.
Line 19: Line 59:
=== eval() ===

In Matlab or IDL the passing of functions to functions works only with a detour using {{{feval()}}} or {{{Call_function()}}}

 * [[http://groups.google.com/group/comp.lang.idl-pvwave/browse_thread/thread/acf94d8f621caf95/47decec322cf5094?q=function+parameters&rnum=4|IDL passing functions to functions]]
 
Of course, this way is possible in Python as well using the {{{eval()}}} function.

Functions

Function with one argument

In [124]: def quadrat(x):
   .....:     return x**2
   .....:

In [125]: quadrat(2)
Out[125]: 4

Function with variable number of arguments

In [126]: def printargs(*args):
   .....:     for arg in args:
   .....:         print arg
   .....:

In [127]: printargs(a)
[1, 2, 3]

In [128]: printargs(a,range(4))
[1, 2, 3]
[0, 1, 2, 3]

Function with variable number of keywords

In [131]: def printkeys(**kw):
   .....:     for k in kw.keys():
   .....:         print k,kw[k]
   .....:

In [132]: printkeys(key1=10,key2='Hallo')
key2 Hallo
key1 10

Function with functions as arguments

Functions can be passed to functions as arguments.

   1 from scipy import sin,pi
   2 
   3 def func(x,f):
   4         return f(x)
   5 
   6 print func(pi/2,sin)

eval()

In Matlab or IDL the passing of functions to functions works only with a detour using feval() or Call_function()

Of course, this way is possible in Python as well using the eval() function.

Lambda expressions

Lambda expressions are (anonymous) one line functions

   1 l=lambda x: x**2-1
   2 l(4)

LehreWiki: SiaProgrammingPythonFunctions (last edited 2008-04-14 10:54:03 by anonymous)