Seite - 87 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 87 -
Text der Seite - 87 -
4.1 Functions:HowtoWriteThem? 87
function argumentf insum_funcion_values(f, start, stop)will act as the
local“nick-name”(insidethefunctionsum_funcion_values)foranyfunctionthat
isusedasfirst argumentwhencallingsum_funcion_values.
Executing theprogram,gives theexpectedprintoutas
Sum with f becomes 6
Sum with g becomes 14
4.1.9 LambdaFunctions
A one-line function may be defined in a compact way, as a so-called lambda
function.Thismaybe illustratedas
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,
whencallingsum_function_valuesfromabovewith lambdafunctionsreplacing
the functionsfandg:
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 formofa lambdafunction is thus
function_name = lambda arg1, arg2, ... : <some_expression>
# ...which is equivalent to:
def function_name(arg1, arg2, ...):
return <some_expression>
The general syntax consists of the reserved wordlambda, followed by a series of
parameters, thenacolon,and,finally,somePythonexpressionresultinginanobject
tobe returnedfromthe function.
4.1.10 AFunctionwithSeveralReturnStatements
It ispossible tohaveseveralreturnstatements ina function,as illustratedhere:
def check_sign(x):
if x > 0:
return ’x is positive’
elif x < 0:
return ’x is negative’
else:
return ’x is zero’
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik