Seite - 33 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 33 -
Text der Seite - 33 -
2.2 Functions 33
one single return statement. Be prepared for critical comments if you return
whereveryouwant...
Anexpressionyouwilloftenencounterwhendealingwithprogramming,ismain
program,or thatsomecodeis inmain. This isnothingparticular toPython,andsim-
ply refers to thatpartof theprogramwhich isoutside functions.However,note that
thedef line of functions is counted intomain. So, inball_function.pyabove,
all statementsoutside the functionyare inmain, andalso the linedef y(t):.
A functionmay take no arguments, ormany, inwhich case they are just listed
within the parentheses (following the function name) and separated by a comma.
Let us illustrate. Take a slight variation of the ball example and assume that the
ball isnot thrownstraightup,butat anangle, so that twocoordinatesareneeded to
specify itspositionatany time.According toNewton’s laws (whenair resistance is
negligible), theverticalposition isgivenbyy.t/Dv0yt 0:5gt2andthehorizontal
positionbyx.t/Dv0xt.Wecan includeboth theseexpressions inanewversionof
ourprogram that prints thepositionof theball for chosen times. Assumewewant
to evaluate these expressions at two points in time, t D 0:6s and t D 0:9s. We
canpick somenumbers for the initial velocity componentsv0yandv0x, name the
programball_position_xy.py,andwrite it forexampleas
def y(v0y, t):
g = 9.81 # Acceleration of gravity
return v0y*t - 0.5*g*t**2
def x(v0x, t):
return v0x*t
initial_velocity_x = 2.0
initial_velocity_y = 5.0
time = 0.6 # Just pick one point in time
print x(initial_velocity_x, time), y(initial_velocity_y, time)
time = 0.9 # ... Pick another point in time
print x(initial_velocity_x, time), y(initial_velocity_y, time)
Nowwecomputeandprint the twocomponents for theposition, for eachof the
two chosen points in time. Notice how each of the two functions now takes two
arguments. Running theprogramgives theoutput
1.2 1.2342
1.8 0.52695
Afunctionmayalsohaveno returnvalue, inwhichcasewesimplydrop the re-
turnstatement,oritmayreturnmorethanonevalue. Forexample, thetwofunctions
we just definedcouldalternativelyhavebeenwrittenasone:
def xy(v0x, v0y, t):
g = 9.81 # acceleration of gravity
return v0x*t, v0y*t - 0.5*g*t**2
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik