Page 49 - Python Basics: A Practical Introduction to Python 3
P. 49

3.2. Mess Things Up


            Syntax Errors

            A syntax error occurs when you write code that isn’t allowed in the
            Python language.

            Let’s create a syntax error by removing the last quotation mark from
            the code in the hello_world.py file that you created in the last section:

            print("Hello, World)


            Save the file and press F5 to run it. The code won’t run! IDLE dis-
            plays an alert box with the following message:


            EOL while scanning string literal.

            There are two terms in this message that may be unfamiliar:

            1. A string literal is text enclosed in quotation marks.  "Hello,
               World" is a string literal.
            2. EOL stands for end of line.


            So, the message tells you that Python got to the end of a line while
            reading a string literal. String literals must be terminated with a quo-
            tation mark before the end of a line.

            IDLE highlights the line containing print("Hello, World) in red to help
            you quickly find the line of code with the syntax error. Without the
            second quotation mark, everything after the first quotation mark—
            including the closing parenthesis—is part of a string literal.


            Runtime Errors

            IDLE catches syntax errors before a program starts running. In con-
            trast, runtime errors only occur while a program is running.

            To generate a runtime error, remove both quotation marks in the
            hello_world.py file:





                                                                          48
   44   45   46   47   48   49   50   51   52   53   54