2

Version: Python 3.3.2 (default, Sep 11 2013, 20:16:42)

Hey, I'm doing some tests with python, fiddling a bit with the shell, but I get a strange error.

>>> a = 5
>>> if a > 0:  
...     print("a is a positive number.")
... if a < 0:
  File "<stdin>", line 3
    if a < 0:
     ^
SyntaxError: invalid syntax

I don't know why this error appears. I know I can use elif or else, but I just want to test. Help?

1

4 Answers 4

4

This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.

The handy rule of thumb here is that you can't start a new block with if, def, class, for, while, with, or try unless you have the >>> prompt.

0

Are you pressing backspace to enter the second if? The shell doesn't like that. It's expecting another line in the logic block, or to be able to execute the block (by pressing enter one more time). The shell can only execute one block at a time, i.e. finish the first if first, then you can enter the second if. You can use elif because it's still considered part of the same logic block.

0

The REPL is still working on the previous code block. Enter an empty line on its own to terminate it first.

0

You need a blank line after your print statement, the Python interpreter thinks you're continuing a block until you do that, so you get an indentation error on your second if statement. This is not "invalid", the interactive interpreter is designed to work that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.