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

(singke) #1

print function.


The error generated in Listing 17.1 came from issuing a single syntactically incorrect statement in the
Python interactive shell. A syntax error message looks slightly different when it is generated by a
Python statement within a script. Listing 17.2 shows an example.


LISTING 17.2 A Syntax Error in a Script


Click here to view code image


pi@raspberrypi ~ $ python3 py3prog/my_errors.py
File "py3prog/my_errors.py", line 17
print ("I love my Raspberry Pi!)
^
SyntaxError: EOL while scanning string literal
pi@raspberrypi ~ $

The SyntaxError line of Listing 17.2 is identical to the SyntaxError line of Listing 17.1.
However, the first line of the error message denotes the name of the script that has the syntax error as
well as the line number in the script where it occurred. Having the line number is very helpful when
you’re tracking down syntax errors in your scripts!


By the Way: File Name
When a syntax error occurs in the Python interactive shell, the interpreter tells you that
the file is <stdin> and the line is line 1. This is because a script file is not being
used. Instead, the shell is getting Python statements from you interactively.

There is a little trick you can use to help find a raised syntax error quickly in your script. Use the
Linux shell cat -n command to display your script, as shown in Listing 17.3.


LISTING 17.3 A Trick to Display Script Line Numbers


Click here to view code image


pi@raspberrypi ~ $ cat -n py3prog/my_errors.py
1 # my_errors.py - Demonstrates various Python errors
2 # Written by Blum and Bresnahan
3 #
4 #####################################################
5 #
6 ############# Initialize Variables ##################
7 #
8 my_error = 0
9 num_1 = 3
10 num_2 = 4
11 zero = 0
12 #
13 ############# Error Functions ########################
14 #
15 def missing_quote ():
16 print ()
17 print ("I love my Raspberry Pi!)
Free download pdf