4 - The core Python language II
Published online by Cambridge University Press: 05 February 2016
Summary
This chapter continues the introduction to the core Python language started in Chapter 2 with a description of Python error handling with exceptions, the data structures known as dictionaries and sets, some convenient and efficient idioms to achieve common tasks, and a survey of some of the modules provided in the Python standard library. Finally, we present a brief introduction to object-oriented programming with Python.
Errors and exceptions
Python distinguishes between two types of error: Syntax errors and other exceptions. Syntax errors are mistakes in the grammar of the language and are checked for before the program is executed. Exceptions are runtime errors: conditions usually caused by attempting an invalid operation on an item of data. The distinction is that syntax errors are always fatal: there is nothing the Python compiler can do for you if your program does not conform to the grammar of the language. Exceptions, however, are conditions that arise during the running of a Python program (such as division by zero) and a mechanism exists for “catching” them and handling the condition gracefully without stopping the program's execution.
Syntax errors
Syntax errors are caught by the Python compiler and produce a message indicating where the error occurred. For example,
>>> for lambda in range(8):
File “<stdin>”, line 1
for lambda in range(8):
^
SyntaxError: invalid syntax
Because lambda is a reserved keyword, it cannot be used as a variable name. Its occurrence where a variable name is expected is therefore a syntax error. Similarly,
>>> for f in range(8:
File “<stdin>”, line 1
for f in range(8:
^
SyntaxError: invalid syntax
The syntax error here occurs because a single argument to the range built-in must be given as an integer between parentheses: the colon breaks the syntax of calling functions and so Python complains of a syntax error.
Because a line of Python code may be split within an open bracket (“()”, “[]”, or “﹛﹜”), a statement split over several lines can sometimes cause a SyntaxError to be indicated somewhere other than the location of the true bug.
- Type
- Chapter
- Information
- Learning Scientific Programming with Python , pp. 102 - 159Publisher: Cambridge University PressPrint publication year: 2016