Seite - 74 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 74 -
Text der Seite - 74 -
74 3 LoopsandBranching
3.4 Exercises
Exercise3.1:AforLoopwith Errors
Assume some program has been written for the task of adding all integers i =
1,2,.. .,10andprinting thefinal result:
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sum = Sum + x
print ’sum: ’, sum
a) Identify theerrors in theprogramby just reading thecode.
b) Write a newversionof the programwith errorscorrected.Run thisprogramand
confirmthat it gives thecorrectoutput.
Filename:for_loop_errors.py.
Exercise3.2:TherangeFunction
Write a slightly different version of the program in Exercise 3.1. Now, therange
function should be used in the for loop header, and only the even numbers from
[2,10]shouldbeadded.Also, the (only)statementwithin the loopshould readsum
= sum + i.
Filename:range_function.py.
Exercise3.3:Awhile Loop withErrors
Assume some program has been written for the task of adding all integers i =
1,2,.. .,10:
some_number = 0
i = 1
while i < 11
some_number += 1
print some_number
a) Identify theerrors in theprogramby just reading thecode.
b) Write a newversionof the programwith errorscorrected.Run thisprogramand
confirmthat it gives thecorrectoutput.
Filename:while_loop_errors.py.
Exercise3.4:while LoopInstead of forLoop
Rewriteaverage_height.pyfromSect.3.1.3,usingawhile loop instead.
Filename:while_instead_of_for.py.
Exercise3.5:CompareIntegersaand b
Explainbriefly, in yourownwords,what the followingprogramdoes.
a = int(input(’Give an integer a: ’))
b = int(input(’Give an integer b: ’))
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