Page - 98 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 98 -
Text of the Page - 98 -
98 4 FunctionsandtheWritingofCode
b) Typeinthecodeandruntheprogramtoconfirmthatyourpredictionsarecorrect.
Filename:read_code_1.py.
Exercise4.3:ReadingCode2
a) Read the followingcode and predict the printout producedwhen the programis
executed.
def f(x):
if x < 2:
return 0
else:
return 2*x
x = 0
for i in range(0, 4, 1):
x += i
print(x)
for i in range(0, 4, 1):
x += i*i
print(x)
for i in range(0, 4, 1):
print(f(3*i-1))
b) Typeinthecodeandruntheprogramtoconfirmthatyourpredictionsarecorrect.
Filename:read_code_2.py.
Exercise4.4:Functions forCircumferenceandAreaofaCircle
Writeaprogramthattakesacircleradiusrasinputfromtheuserandthencomputes
the circumferenceC and areaAof the circle. Implement the computationsofC and
Aas twoseparatefunctions thateach takesras inputparameter.PrintCandA to the
screenalongwithanappropriate text.Run theprogramwith r=1andconfirmthat
youget the rightanswer.
Filename:functions_circumference_area.py.
Exercise4.5:FunctionforAdding Vectors
Writea functionadd_vectors that takes2vectors(arrayswithoneindexareoften
calledvectors)aandbas inputargumentsandreturnsthevectorc,wherec=a+b.
Place the function in a little program that calls the function and prints the result.
Thefunctionshouldcheckthataandbhavethesamelength. Ifnot,Noneshouldbe
returned.Confirmthatyour functionworksbycomparing tohandcalculations(i.e.,
just choosesomearraysand test).
Filename:add_vectors.py.
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