[Tutor] if then statements
Steven D'Aprano
steve at pearwood.info
Wed Apr 29 13:27:21 CEST 2015
On Tue, Apr 28, 2015 at 08:24:57PM -0500, Jacqueline G Solis wrote:
> hello,
>
> I keep getting a syntax error. Could you please explain why that
> happens and how to correct it.
Syntax errors are sometimes a bit tricky. Usually, they tell you were
the error is:
py> if (x + 1:
File "<stdin>", line 1
if (x + 1:
^
SyntaxError: invalid syntax
Notice the blank line immediately before "SyntaxError"? If you look
carefully, you will see a caret ^ which points to the ":" colon in the
line before. (In your email, it may not quite line up correctly, but in
the Python interpreter and the console, they should like up.) That
should make it obvious that I am missing a closing parenthesis before
the colon.
But sometimes Python doesn't notice the syntax error until the line
*after* the actual problem:
py> x = (y + 1
... if x:
File "<stdin>", line 2
if x:
^
SyntaxError: invalid syntax
The actual problem is that I am missing a round bracket in the previous
line, but Python doesn't realise it until it gets to the colon.
Does that help?
--
Steve
More information about the Tutor
mailing list