[Tutor] What's the invalid syntax? Code supplied

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Aug 4 05:26:13 CEST 2005

On Wed, 3 Aug 2005, Nathan Pinno wrote:

> I added a plus sign to show Python to add "\n" or a new line to end of
> the file.

Ok, better.  So the plus sign was necessary in between:




in order to glue them together into one string.

Just for kicks, let's look at another example of a SyntaxError:

>>> def square(x):
...     return x * x
>>> square 42
  File "<stdin>", line 1
    square 42
SyntaxError: invalid syntax

The problematic line:

    square 42

is invalid syntax in the Python language.  (Off-topic tangent: it might
not be necessarily one in a different programming language.)

We know what the problem is: we're missing parens, and in an magical ideal
world, Python would also recognize what we meant, and would say something

    SyntaxError: you're missing parentheses when you're trying to call the
    function.  Try square(42) instead.

But too bad Python's error message aren't as helpful.  *grin* The best
that Python can do, though, is say:

    SyntaxError: invalid syntax

which is sad, but oh well.  But at least Python says that there's a
problem, and points at the '42' to say "I didn't expect that there.  Can
you check around that area?" which is usually enough of a hint.

I guess I'm trying to say: whenever you see a SyntaxError and apply a fix
to it, also take a retrospective moment to also think about what you can
do next time to avoid it, or how to recognize it if it shows its ugly head

Best of wishes!

More information about the Tutor mailing list