#acl AdminGroup:read,write EditorGroup:read All:read #format wiki #language en #pragma section-numbers off = 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. {{{#!python from scipy import sin,pi def func(x,f): return f(x) print func(pi/2,sin) }}} === eval(), apply() === 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()}}} or {{{apply()}}} function. {{{#!python apply(sin,(pi/2,)) f='sin' x=pi/2.0 eval(f+'('+str(x)+')') }}} = Lambda expressions = Lambda expressions are (anonymous) one line functions {{{#!python l=lambda x: x**2-1 l(4) }}} = Mapping = Similar as {{{apply()}}} works with one argument one can call {{{map()}}} with a sequence {{{#!python map(len,['Always','look','on','the','bright','side','of','life']) [6, 4, 2, 3, 6, 4, 2, 4] }}} The following example shows the combined usage of a lambda expression {{{#!python map(lambda s:len(s)+1,['Always','look','on','the','bright','side','of','life']) [7, 5, 3, 4, 7, 5, 3, 5] }}}