简体   繁体   中英

Python throwing out a random invalid syntax error

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?

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.

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

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.

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM