pythonexceptionpython-idle

Why SyntaxError for code after the try/except/finally block in IDLE?


I am novice of Python, now learning using the app SoloLearn

In the in-app code playground I run these codes with no problem: enter image description here

But when I run the same code in IDLE, I get an SyntaxError: enter image description here

Does anyone have any idea why?


Solution

  • This has nothing to do with IDLE as it is, as others said, the normal behavior of interactive Python, which executes one statement at a time.

    >>> try:
    ...   print(10/0)
    ... except:
    ...   print(5)
    ... finally:
    ...   print(6)
    ... print(7)
      File "<stdin>", line 7
        print(7)
            ^
    SyntaxError: invalid syntax
    

    If you put the same code in a file and run the same file in 'batch' mode, it should work fine, whether you run the file from a command line or with IDLE or with any other editor or IDE that will run code in files or an editor buffer.

    Since Code Playground has a Run button, I strongly suspect that it is presenting you with an editor window, similar to IDLE and its Run Module F5 menu/shortcut option, not an interactive shell.