Reputation: 1631
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.
Upvotes: 2
Views: 3897
Reputation: 85035
Are you trying to enter this code in IDLE's default Python Shell
window? You are better off opening an IDLE editor window (menu item File
-> New Window
) and running the code from there (menu item Run
-> Run Module
). Indenting in the shell window can get confusing and it is difficult to correct mistakes.
Upvotes: 1
Reputation: 10170
Insert a newline after print(i)
(also on windows)
x = [1, 2, 3]
for i in x:
print(i)
print('finished')
Upvotes: 1
Reputation: 104020
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
$
Upvotes: 3
Reputation: 2966
Take out all your semicolons.
x = [1,2,3]
for i in x:
print(i)
print('finished')
Upvotes: 1