4.1 Functions: How to Write Them?
87
function argument f in sum_funcion_values(f, start, stop) will act as the
local “nick-name” (inside the function sum_funcion_values) for any function that
is used as first argument when calling sum_funcion_values.
Executing the program, gives the expected printout as
Sum with f becomes 6
Sum with g becomes 14
4.1.9 Lambda Functions
A one-line function may be defined in a compact way, as a so-called lambda
function. This may be illustrated as
g = lambda x: x**2
# ...which is equivalent to:
def g(x):
return x**2
Lambda functions are particularly convenient as function arguments, as seen next,
when calling sum_function_values from above with lambda functions replacing
the functions f and g:
print(sum_function_values(lambda x: x, 1, 3))
print(sum_function_values(lambda x: x**2, 1, 3))
This gives the same output as we got above. In this way, the lambda function is
defined “in” the function call, so we avoid having to define the function separately
prior to the (function) call.
A lambda function may take several comma-separated arguments. A more
general form of a lambda function is thus
function_name = lambda arg1, arg2, ... :
# ...which is equivalent to:
def function_name(arg1, arg2, ...):
return
The general syntax consists of the reserved word lambda, followed by a series of
parameters, then a colon, and, finally, some Python expression resulting in an object
to be returned from the function.
4.1.10 A Function with Several Return Statements
It is possible to have several return statements in a function, as illustrated here:
def check_sign(x):
if x > 0:
return ’x is positive’
elif x < 0:
return ’x is negative’
else:
return ’x is zero’
Précédent

- 108/350

Suivant