Seite - 5 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 5 -
Text der Seite - 5 -
1.2 APythonProgramwithVariables 5
the sign # it takes the rest of the line as a comment. Python then simply skips
reading the rest of the line and jumps to thenext line. In the code, you see several
suchcomments andprobably realize that theymake it easier for you tounderstand
(orguess)what ismeantwith thecode. Insimplecases, commentsareprobablynot
muchneeded,butwill soonbe justifiedas the levelofcomplexity stepsup.
Thenext line readbyPython is
v0 = 5 # Initial velocity
In Python, a statement likev0 = 5 is knownas anassignment statement (very
differentfromamathematicalequation!). Theresultontheright-handside,herethe
integer5,becomesanobjectandthevariablenameonthe left-handside isanamed
referenceforthatobject.Wheneverwewritev0,Pythonwill replaceitbyaninteger
with value5. Doingv1 = v0 creates a newname,v1, for the same integer object
withvalue5andnot acopyofan integerobjectwithvalue5. Thenext two lines
g = 9.81 # Acceleration of gravity
t = 0.6 # Time
areof thesamekind, sohavingread themtoo,Pythonknowsof threevariables (v0,
g, t) and their values. These variables are then used byPythonwhen it reads the
next line, theactual “formula”,
y = v0*t - 0.5*g*t**2 # Vertical position
Again, according to its rules, Python interprets* asmultiplication,- asminus and
** as exponent (let us also add here that, not surprisingly, + and /would have
been understood as addition and division, if such signs had been present in the
expression). Having read the line, Python performs themathematics on the right-
handside,andthenassignstheresult (inthiscasethenumber1.2342)tothevariable
namey. Finally,Pythonreads
print y
This makes Python print the value of y out in that window on the screen where
youstarted theprogram.Whenball.py is run, thenumber1.2342appearson the
screen.
In the codeabove,yousee severalblank lines too. Theseare simply skippedby
Python andyoumayuse asmanyas youwant tomake anice and readable layout
of thecode.
1.2.3 WhyNotJustUseaPocketCalculator?
Certainly,finding theanswerasdoneby theprogramabovecouldeasilyhavebeen
donewith a pocket calculator. No objections to that and no programmingwould
havebeenneeded.However,what if youwould like tohave thepositionof theball
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