Why am I getting a SyntaxError in the Python interpreter?

前端 未结 3 852
天命终不由人
天命终不由人 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: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.

提交回复
热议问题