Python Forum

Full Version: for / else not working in interactive mode
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
this little test script works:
Output:
lt2a/phil /home/phil 137> cat try.py #!/usr/bin/env python3 a=[1,2,3,4,5,6] b=[0,5,10] for x in b: if x in a: print('foo') break else: print('bar') print('xyzzy') lt2a/phil /home/phil 138> python3 try.py foo xyzzy lt2a/phil /home/phil 139>
however, doing the same exact thing interactively gets a syntax error:
Output:
lt2a/phil /home/phil 139> python3 Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a=[1,2,3,4,5,6] >>> b=[0,5,10] >>> for x in b: ... if x in a: ... print('foo') ... break ... else: ... print('bar') ... print('xyzzy') File "<stdin>", line 7 print('xyzzy') ^ SyntaxError: invalid syntax >>>
any idea what is wrong?
The interactive interpreter wants you to end the for loop with a blank line before continuing on with more code:

Output:
>>> for i in range(5): ... print(i) ... print(0) File "<stdin>", line 3 print(0) ^ SyntaxError: invalid syntax >>> for i in range(5): ... print(i) ... 0 1 2 3 4 >>> print(0) 0
that doesn't work, either:

Output:
Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a=[1,2,3,4,9,6] >>> b=[0,5,10] >>> for x in b: ... if x in a: ... print('foo') ... break ... >>> else: File "<stdin>", line 1 else: ^ SyntaxError: invalid syntax >>>
The end of a for/else is after the else block:
>>> a=[1,2,3,4,5,6]
>>> b=[0,5,10]
>>> for x in b:
...     if x in a:
...         print('foo')
...         break
... else:
...     print('bar')
...
foo
>>> print('xyzzy')
xyzzy
why does the interactive interpreter use a different syntax than the script interpreter?