96
4 Functions and the Writing of Code
will be regarded as the final version (in general, however, programs are typically
changed and improved again and again, making it hard to reach the “final” version!).
Developing a Computational Plan
To write a program, you need to plan what that program should do, and a
good plan requires a thorough understanding of the addressed problem. One
fundamentally important thing with the step-wise strategy, is that it invites
you to think through your computational problem very carefully: What bits
and pieces, or “sub-problems”, make up the whole task? Should the “subproblems” be solved in any particular order, i.e., do parts of the problem
depend on results from other parts? What is the best way to compute each
of the “sub-problems”?
This kind of thinking, which combines favorably with discussions among
students/colleagues, often pays off in terms of a much deeper understanding
of the problem at hand. Good solutions often require such an understanding.
Compound Statements
The constructions met in this chapter, and the previous chapter, are characterized by a grouping of statements that generally span several lines (although
it is possible to write simpler cases on a single line, when statements are
separated with a semi-colon). Such constructions are often referred to as
compound statements, having headers (ending with a colon) and bodies (with
indented statements). a
Interactive handling of compound statements is straight forward. For
example, a for loop may be written (and executed) like
In [1]: for i in [1, 2, 3]:
# write header, press enter
...:
print(i)
# indent comes automatically
...:
# press only enter, i.e., finished
1
2
3
When the header has been typed in and we press enter, we are automatically
given the indent on the next line. We can then proceed directly by writing
print(i) and press enter again. We then want to finish our loop, which is
understood when we simply press enter, writing nothing else.
a https://docs.python.org/3/reference/compound_stmts.html.
Précédent

- 117/350

Suivant