Page - 82 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 82 -
Text of the Page - 82 -
82 4 FunctionsandtheWritingofCode
Here, the comment # First line after function definition is after the
function.
The first line in the function body shown here, is an optional documentation
string, a docstring. This string is meant for a human interpreter, so it should say
something about the purpose with the function and explain input parameters and
return values, unless obvious. By convention, a docstring is enclosed in triple
double quotes ("""), which allows the string to run over several lines. When
present, the docstringmust appear immediatelyafter the functionheader, as shown
above.
The code lines of a function are executed only when the function is called (or
invoked), as explained above with ball_function.py. Usually, a function ends
with a return statement, starting with the reserved word return, which “returns”
one or more results back to the place where the function was called. However, the
explicit return statement may be dropped if not needed.3 How to receive multiple
returnvalues froma functioncallwill beexemplified inSect.4.1.6.
Afunctionbodycanhaveloops,branchingandcalls toother functions,andmay
containasmanycodelinesasyouneed.Sometimes,a functionbodycontainsnoth-
ing more than a return statement of the form return <some calculation>,
wheresomecalculation is carriedoutbeforereturningthe result.Note that function
inputparametersarenot required tobenumbers.Anyobjectwill do,e.g., stringsor
other functions.
4.1.3 FunctionsandtheMainProgram
An expression you will often encounter in programming, is main program, or that
some code is “in main”. This is nothing particular to Python, and simply refers to
that part of the programwhich is outside functions, taking functionheadersas part
of the mainprogram.
We may exemplify this withball_function.py from above, using comments
to tell which linesarenot “in main”.
def y(v0, t):
g = 9.81 # not in main
return v0*t - 0.5*g*t**2 # not in main
v0 = 5
time = 0.6
print(y(v0, time))
time = 0.9
print(y(v0, time))
Thus,everything is inmainexcept the two linesof the functionbody.
3 In that case, something calledNone is returned, being a certain object that represents “nothing”.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik