Why am I getting a SyntaxError in the Python interpreter?

前端 未结 3 806
天命终不由人
天命终不由人 2020-12-21 16:57

This code works when I try it from a .py file, but fails in the command line interpreter and Idle.

>>> try:
...     fsock = open(\"/bla\")
... excep         


        
相关标签:
3条回答
  • 2020-12-21 17:16

    With Python 3, print is a function and not a statement, so you would need parentheses around the arguments, as in print("continue"), if you were using Python 3.

    The caret, however, is pointing to an earlier position than it would be with Python 3, so you must be using Python 2.x instead. In this case, the error is because you are entering this in the interactive interpreter, and it needs a little "help" to figure out what you are trying to tell it. Enter a blank line after the previous block, so that it can decipher the indentation properly, as in this:

    >>> try:
    ...     fsock = open("/bla")
    ... except IOError:
    ...     print "Caught"
    ...
    (some output shows here)
    >>> print "continue"
    
    0 讨论(0)
  • 2020-12-21 17:26

    Try this one in the interpreter:

    try:
        fsock = open("/bla")
    except IOError:
        print "Caught"
    
    print "continue"
    

    Important here is the empty line after the indentation. I'm using the python 2.6 interpreter and it throws the same Syntax error as you.

    This is because the interpreter expects single blocks separated by blank lines. Additionally the blank line (two new line characters) indicates the end of the block and that the interpreter should execute it.

    0 讨论(0)
  • 2020-12-21 17:30

    You need to leave a blank line to close the except block. The ... indicates it is still trying to put code in that block, even though you dedent it. This is just a quirk of the interactive interpreter.

    0 讨论(0)
提交回复
热议问题