Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
18 #
...

Using the cat -n command causes Python to display line numbers on the screen for each line in
your script. In Listing 17.3, you can easily find line 17, where the syntax error occurred. You can see
that the print statement on that line does not have the closing double quote!


Did You Know: Jump to It
You can quickly jump to a line with a syntactical error by using the nano text editor.
You use the syntax nano +line_number file_name. nano opens up the script and goes
directly to the line number you specified. For example, to go to directly to line number
17 in the file py3prog/my_errors.py, enter nano +17
py3prog/my_errors.py.
In the IDLE 3 editor, you can quickly jump to a line with a syntactical error by pressing
the key combination Alt+G. A little window opens, asking which line number to go to.
Simply type in the line number and press the Enter key.

As you have learned, the Python interpreter finds syntactical errors when it reads each Python
statement within a script and checks its syntax. If no errors are found, the Python interpreter translates
the statements into something called bytecode. When the translation is complete, the bytecode is
handed off to the Python virtual machine to run. At this point, a new type of error exception can be
raised.


Runtime Error Exceptions


A runtime error is raised when the Python script is running and an error occurs. Often such an error
causes the script to halt immediately and produce a traceback. A traceback is an error message that,
as its name says, traces back to the original runtime error.


By the Way: Illogical Runtime Errors
Runtime errors can come in a couple different flavors. One flavor is a logic error. A
logic error may cause a script to halt, or it may just produce undesirable results. Logic
errors are called logic errors because they are attributed to illogical thinking on the
part of the script writer.

A classic runtime error is trying to divide a number by zero, which is mathematically incorrect. (You
math wizards know that dividing by zero is better described as undefined.) In Listing 17.4, there are
no problems in the Python interactive shell, when the number 3 is divided by the number 4 on lines 2
through 7.


LISTING 17.4 Divide-by-Zero Example


Click here to view code image


1: >>>
2: >>> num1=3
Free download pdf