Seite - 44 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 44 -
Text der Seite - 44 -
44 2 AFewMoreSteps
PythonisBoth DynamicallyandStronglyTyped
Python is a dynamically typed language, since a certain variable name may
refer to objects of different types during the execution of a program. This
means that writing
In [1]: z = 10 # z refers to an integer
In [2]: z = 10.0 # z refers to a float
In [3]: z = ’some string’ # z refers to a string
is perfectly fine and we get no error messages. In statically typed languages
(e.g.,C and Fortran), this would not be accepted, since a variable then would
have tobe ofoneparticular type throughout.
Python is also a strongly typed language, since it is strict about how you
cancombineobject types:
In [1]: ’yes’ + ’no’ # add two strings
Out[1]: ’yesno’
In [2]: ’yes’ + 10 # ...try adding string and integer
Traceback (most recent call last):
File "<ipython-input-5-fdfd15f88bd0>", line 1, in <module>
’yes’ + 10
TypeError: cannot concatenate ’str’ and ’int’ objects
Adding two strings is straight forward, but trying the same with a string
and an integer gives an error message, since it is not well defined.
In a weakly typed language, this could very well give yes10 without
any error message. If so, it would be based on a (vaguely) founded
assumption that this is what the programmer intended (but perhaps it
is just as likely an error?). For more details on these matters, see, e.g.,
https://en.wikipedia.org/wiki/Python_(programming_language).
2.2.6 OperatorPrecedence
When the arithmetic operators+, -, *, / and ** appear in an expression, Python
gives thema certainprecedence.Python interprets the expressionfromleft to right,
takingoneterm(partofexpressionbetweentwosuccessive+or-)ata time.Within
each term,** isdonebefore*and/.
Consider the expressionx = 1*5**2 + 10*3 - 1.0/4.Thereare three terms
here and interpreting this, Python starts from the left. In the first term,1*5**2, it
first does5**2which equals 25. This is then multiplied by 1 to give 25 again. The
secondtermis10*3, i.e.,30.So thefirst twotermsaddupto55.Thelast termgives
0.25,so thefinal result is54.75whichbecomes thevalueofx.
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