Page - 74 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 74 -
Text of the Page - 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, 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