Page - 61 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 61 -
Text of the Page - 61 -
3.1 TheforLoop 61
This means that if we had, e.g., switched the print command inside our loop with
print(βHello!β) (i.e., so that i does not appear explicitly within the loop), i
wouldstill run throughthenumbers1 to10asbefore,butHello!wouldbeprinted
10 times instead.
The loopvariablei takeson the values1 to 10 in theorder listed, andanyorder
wouldbeacceptable to Python.Thus, if we (for some reason)would like to reverse
theorderof theprintouts,wecouldsimplyreversethe listofnumbers,writing[10,
9, 8, 7, 6, 5, 4, 3, 2, 1] instead.
It shouldbenoted that the loopvariable isnot restricted to runover integers.Our
nextexample includes loopingalsooverfloatingpointvalues.
IndentationandNestedLoops Inoursimple times tableexampleabove, theprint
command inside the loop was indented 4 spaces, which is in accordance with the
official style guideofPython.2
Strictly speaking, the style guide recommends an indent of 4 spaces per
indentation level. What this means, should become clear if we demonstrate how
a for loop may appear within another for loop, i.e., if we show an arrangement
withnested loops.
for i in [1, 2, 3]:
# First indentation level (4 spaces)
print(βi = {:d}β.format(i))
for j in [4.0, 5.0, 6.0]:
# Second indentation level (4+4 spaces)
print(β j = {:.1f}β.format(j))
# First line AFTER loop over j
# First line AFTER loop over i
The meaning of indentation levels should be clear from the comments (see code),
and it is straight forward to use more nested loops than shown here (see, e.g.,
Exercise 5.7). Note that, together with the colon, indenting is part of the syntax
also for other basic programmingconstructions in Python (e.g., inif-elif-else
constructionsand functions).
Whenexecuting thenested loopconstruction,weget thisprintout:
i = 1
j = 4.0
j = 5.0
j = 6.0
i = 2
j = 4.0
j = 5.0
j = 6.0
i = 3
j = 4.0
j = 5.0
j = 6.0
From the printout, we may infer how the execution proceeds. For each value of
i, the loop over j runs through all its values before i is updated (or the loop is
terminated). To test your understanding of nested loops, you are recommended to
doExercise5.1.
2 https://www.python.org/dev/peps/pep-0008/.
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