Page - 88 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 88 -
Text of the Page - 88 -
88 4 FunctionsandtheWritingofCode
Remember that only one of the branches is executed for a single call to
check_sign, so depending on the number x, the return may take place from
anyof the three returnalternatives.
To Returnat theEnd or Not
Programmers disagree whether it is a good idea to use return inside a
function, or if there should be just a single return statement at the end of
the function.Theauthorsof thisbookemphasize readablecodeand think that
returncan be useful in branchesas in the exampleabovewhen the function
is short. For longer or more complicated functions, it might be better to have
onesinglereturn statementat theend.
NestedFunctions
Functions may also be defined within other functions. In that case, they
become localfunctions,ornestedfunctions,knownonlytothefunctioninside
which theyaredefined.
Functions defined in main are referred to as global functions. A nested
functionhasfullaccess toallvariables in theparent function, i.e. the function
withinwhich it isdefined.
OverheadofFunctionCalls
Function calls have the downside of slowing down program execution.
Usually, it is a good thing to split a program into functions, but in very
computing intensive parts, e.g., inside long loops, one must balance the
convenienceofcallingafunctionandthecomputationalefficiencyofavoiding
functioncalls. It isagoodrule todevelopaprogramusingplentyof functions
and then in a later optimization stage, when everything computes correctly,
removefunctioncalls thatarequantifiedtoslowdownthecode.Let itbeclear,
however, that newcomers to programming should focus on writing readable
code,not fast code!
In Sect.5.6, we investigate (for a particular case) the impact that function
callshaveonCPU time.
4.2 ProgrammingasaStep-WiseStrategy
When students start out with programming, they usually pick up the basic ideas
quite fast and learn to read simpler code rather swiftly. However,when it comes to
thewritingofcode,manyfind ithard toevenget started.
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