Seite - 97 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 97 -
Text der Seite - 97 -
4.3 Exercises 97
4.3 Exercises
Exercise4.1:ErrorswithColon, Indent, etc.
Write the program ball_function.py as given in the text and confirm that the
program runs correctly. Then save a copy of the program and use that program
during the followingerror testing.
Youaresupposedtointroduceerrorsinthecode,onebyone.Foreacherrorintro-
duced, save and run the program,and comment how well Python’s response corre-
sponds to the actualerror.Whenyouarefinishedwithoneerror, re-set theprogram
tocorrectbehavior (andcheck that it works!)beforemovingon to thenexterror.
a) Change the first line fromdef y(v0, t): todef y(v0, t), i.e., remove the
colon.
b) Removethe indent in frontof thestatementg = 9.81 inside thefunctiony, i.e.,
shift the text fourspaces to the left.
c) Now let the statementg = 9.81 inside the functiony have an indent of three
spaces (while the remainingtwo linesof the functionhavefour).
d) Remove the left parenthesis in the first statementdef y(v0, t):
e) Change the first line of the function definition from def y(v0, t): to def
y(v0):, i.e., removethe parametert (and thecomma).
f) Change the first occurrence of the command print(y(v0, time)) to
print(y(v0)).
Filename:errors_colon_indent_etc.py.
Exercise4.2:ReadingCode1
a) Read the followingcode and predict the printout producedwhen the programis
executed.
def f(x):
return x**2
def g(x):
return 2*x
for x in [1, 5, 6, 9]:
if x < 5:
# case 1
print(f(x))
elif x == 5:
# case 2
print(2*f(x))
elif x > 5 and x < 8:
# case 3
print(f(x+4) + g(x*2) - g(2))
else:
# case 4
y = x + 2
print(g(y))
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