Syntax Errors

In this book, and with the approach we are taking with test driven development, we cannot accomodate Syntax Errors.

Syntax Errors are are kind of errors that does not follow the Rules of valid python program

For instance there are rules of variable names like

  1. Cannot start with a number

  2. Should only have alpha-numeric characters, and "_"

  3. Should not be a keyword of the language.

If we have a variable name with any of these, program will result in a syntax error.

Tests for Syntax Errors

1var = "invalid variable name"

The error message will be

$ python syntax_errors/invalid_variable_1.py 
  File "syntax_errors/invalid_variable_1.py", line 2
    1var = "invalid variable name"
       ^
SyntaxError: invalid syntax

Another example invalid syntax.

$var = "invalid variable name"

The output

It is interesting to note that $ might be an allowed character in variable names in other languages.

A syntax error where we end up using a reserved key-word.

This will end up with the same Syntax Error.

Errors while overriding builtins

Keywords are the building blocks of the language. Besides keywords, python includes set of builtins terms that any which are defined already by the interpreter. Python will not through a SyntaxError for overriding a builtin, but it will result in a unexpected run-time error or sometimes mysterious behavior.

Here is example program wherein we have overridden the builtin variable len.

This the error printed by the program.

The first time, len is used, it will give the length of the string, the second time, the len is used, it will give a TypeError and not SyntaxError.

Fixing Syntax Errors

And exercising this program will not give any syntax errors.

Keywords and builtins

The list of reserved by python keywords can be examined using the help() command in the interpreter.

  • Go to the interactive help()

  • Type keywords

Similarly, the builtins can be listed using the interpreter using the dir() call on __builtins__.

Our test driven programs will not have a SyntaxError or errors due to overwriting builtin names. These errors are easiest to catch and should be fixed immediately.

Last updated

Was this helpful?