Search code examples
pythonpython-idle

Syntax error in Python IDLE (Mac OS X) because of indentation


I'm assuming this is going to be stupidly easy to answer, yet I've searched all over and can't find an answer. I'm learning Python and trying to run some very simple code, but I keep getting a syntax error any time I try to do something after an indented block. For example:

x = [1,2,3];
for i in x:
    print(i);
print('finished');

When I run this code, I get a syntax error on the print('finished') part. Any time I try to run anything by unindenting after a block like a loop or if statement, I get this error. I'm running Python 3.2.3 in IDLE on Mac OS X Lion.

UPDATE: seems this wasn't as easy as I thought and maybe I'm trying to get something to work that is pointless. I guess the shell only runs multiline statements when you're running a block that indents, but the moment you get back to the top level it executes the statements. Since I'll usually be working with files, most likely in Django, won't matter in the end. Thanks for all the amazingly fast responses though.


Solution

  • At least the python interactive interpreter on my Ubuntu system requires a newline to end the block:

    >>> x = [1,2,3];
    >>> for i in x:
    ...     print(i);
    ... print('finished');
      File "<stdin>", line 3
        print('finished');
            ^
    SyntaxError: invalid syntax
    >>> x = [1,2,3];
    >>> for i in x:
    ...     print(i);
    ... 
    1
    2
    3
    >>> print('finished');
    finished
    

    Funny enough, the python interpreter does not require the blank line when run on scripts:

    $ cat broken.py 
    #!/usr/bin/python
    
    x = [1,2,3];
    for i in x:
        print(i);
    print('finished');
    
    $ ./broken.py 
    1
    2
    3
    finished
    $