When I run a simple loop, and I try to perform some operation after the end of the loop, I get a syntax error (see sample). It happens no matter how simple or complicated the loop is, or what statement I enter after the loop
a=2
for i in range(1,10):
… a=a+2
… print (i,a)
… if a==6:
… print(i,a)
…
… for j in range (1,3):
File “”, line 7
for j in range (1,3):
^^^
SyntaxError: invalid syntax
print (j)
This transcript shows a ... prompt after the blank line which should
have marked off the end of things for the Python interactive mode.
I don’t suppose there are some spaces on that apparently blank line?
>>> for i in range(1,10):
... a=a+2
... print (i,a)
... if a==6:
... print(i,a)
...
... for j in range (1,3):
File "<stdin>", line 7
for j in range (1,3):
^^^
SyntaxError: invalid syntax
>>> print (j)
Notionally we’d expact a fresh >>> prompt after that blank line,
ready for a new statement. Like this:
>>> a=0
>>> for i in range(1,10):
... a=a+2
... print (i,a)
... if a==6:
... print(i,a)
...
1 2
2 4
3 6
3 6
4 8
5 10
6 12
7 14
8 16
9 18
>>>
That you’ve got a ... prompt suggests that Python thinks the statement
is incomplete (I’m guessing some spaces there). This means that it
expects the next statement to be part of the for loop, so it should
be indents 3 spaces like the rest.
This behaviour is a bit of a hack in the interactive mode to help mark
off the end of compound statements, and isn’t quite like Python-in-a-script.