110
5 Some More Python Essentials
If we try to use an uninitialized variable, a NameError exception is raised:
In [1]: print(x)
# x is uninitialized
...
...
NameError: name ’x’ is not defined
When division by zero is attempted, it results in a ZeroDivisionError exception:
In [2]: 1.0/0
...
...
ZeroDivisionError: float division by zero
Using illegal indices causes Python to raise an IndexError exception.:
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
Wrong Python grammar, or wrong typing of reserved words, gives a SyntaxError
exception:
In [6]: impor numpy as np
# typo... missing t in import
...
impor numpy as np
^
SyntaxError: invalid syntax
If object types do not match, Python raises a TypeError exception:
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
forwardly concatenated with +.)
Abort Execution with sys.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 module a (a
module with functions and parameters that are specific to the system). For
an application of sys.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
regarded as) the “final” version. To test our times tables program, we should check
Précédent

- 131/350

Suivant