Why do I get the syntax error “SyntaxError: invalid syntax” in a line with perfectly valid syntax?

When an error is reported on a line that appears correct, try removing (or commenting out) the line where the error appears to be. If the error moves to the next line, there are two possibilities:

  • Either both lines have a problem (and the second may have been hidden by the first); or
  • The previous line has a problem which is being carried forward.

The latter is more likely, especially if removing another line causes the error to move again.

For example, code like the following, saved as twisty_passages.py:

xyzzy = (1 +
plugh = 7

will produce an error on line 2, even though the problem is clearly caused by line 1:

  File "twisty_passages.py", line 2
    plugh = 7
          ^
SyntaxError: invalid syntax

The code in the question has a similar problem: the code on the previous line has unbalanced parentheses. Annotated to make it clearer:

# open parentheses: 1  2             3
#                   v  v             v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
#                               ^             ^
# close parentheses:            1             2

There isn’t really a general solution for this – the code needs to be analyzed and understood, in order to determine how the parentheses should be altered.

Leave a Comment