Seite - 110 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 110 -
Text der Seite - 110 -
110 5 SomeMorePythonEssentials
Ifwe try touseanuninitializedvariable, aNameErrorexception is raised:
In [1]: print(x) # x is uninitialized
...
...
NameError: name ’x’ is not defined
Whendivisionbyzero is attempted, it results inaZeroDivisionErrorexception:
In [2]: 1.0/0
...
...
ZeroDivisionError: float division by zero
Using illegal indicescausesPython to raise anIndexErrorexception.:
In [3]: x = [7, 8, 9]
In [4]: x[2]
Out[4]: 9
In [5]: x[3] # legal indices are 0, 1 and 2
...
...
IndexError: list index out of range
WrongPythongrammar,orwrong typingof reservedwords,givesaSyntaxError
exception:
In [6]: impor numpy as np # typo... missing t in import
...
impor numpy as np
^
SyntaxError: invalid syntax
Ifobject typesdonotmatch,PythonraisesaTypeErrorexception:
In [7]: ’a string’ + 1 # attempt to add string and integer
...
...
TypeError: must be str, not int
(We might add that, in the last example here, two strings could have been straight
forwardlyconcatenatedwith+.)
AbortExecutionwithsys.exit
In some cases, it is desirable to stop execution there and then. This may
be done effectively by use of the exit function in the sys modulea (a
module with functions and parameters that are specific to the system). For
anapplicationofsys.exit, see Sect. 7.2.2.
a https://docs.python.org/3/library/sys.html.
We have been careful to check code behavior in a step-wise fashion while
developing our program. Still, testing should be done also with (what, for now, is
regardedas) the “final” version.To test our times tables program,we should check
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