If this isn't the IndentationError
that jramirez's answer fixes, but rather an actual SyntaxError
, it's probably a problem with the line before the if
statement.
In Python, you can continue an expression across multiple lines, as long as the expression is inside parentheses. So, if you accidentally leave off a )
at the end of a function call, or a tuple, or anything else, you often get a mysterious SyntaxError
on the next line. For example, this code:
foo = (1, 2
if a == 2:
pass
… will give this error:
if a == 2:
^
SyntaxError: invalid syntax
And just adding another comma moves the error somewhere different!
foo = (1, 2,
if a == 2:
pass
if a == 2:
^
SyntaxError: invalid syntax
Why? Well, even when you understand exactly what these errors mean, they still aren't very helpful. So first, remember:
If you get a SyntaxError
on a perfectly valid line, look for a missing )
(or ]
or }
, or an extra \
, or a few other special cases) on the line above.
And if you can get an editor that helps you match up parentheses and brackets, it will make this problem much less likely. (For example, with emacs, at least the way I have it set up, it'll automatically try to indent the if
line 7 characters for me, and if I "fix" it it'll fight back against me, and eventually it'll be hard not to notice something is wrong. Then I point at the first (
and it tells me it's unmatched.)
But if you want to know, here goes:
The first version builds a tuple with the value 1
, then a value starting with 2
and continuing onto the next line. 2 if a == 2
is a perfectly good beginning for a ternary if
expression, but 2 if a == 2:
is not; the colon forces it to be an if
statement, and you can't put a statement in the middle of an expression.
The second version builds a tuple with the value 1
, the value 2
, and more values continuing on the next line. if
cannot be the start of any valid expression, so you get the SyntaxError
earlier. But still not early enough to be useful, of course.