>>> query='';for var in xrange(9):\n\tquery+=str(var)
File "<stdin>", line 1
query='';for var in xrange(9):\n\tquery+=str(var)
^
SyntaxError: invalid syntax
>>> query='';for var in xrange(9): query+=str(var)
File "<stdin>", line 1
query='';for var in xrange(9): query+=str(var)
^
SyntaxError: invalid syntax
Why wont the above code work? But the following works
>>> query=""
>>> for var in xrange(9): query+=str(var)
...
>>> query
'012345678'
>>>
The ; is only allowed to combine "small statements". Those are expressions, print, and the like. A for loop, on the other hand, is a compound statement. See the Full Grammar Specification:
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
...
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
In your example, if this is more than just to illustrate your question, you could rewrite it as
query = ''.join(str(var) for var in xrange(9))
Or if you really really need to exec that multiline statement, you can add a \n between the assignment and the for loop (as you already did in another place):
>>> exec("query=''\nfor var in xrange(9):\n\tquery+=str(var)\nprint query")
012345678
But note that this does only work in exec, not in the interactive shell directly:
>>> query=''\nfor var in xrange(9):\n\tquery+=str(var)\nprint query
SyntaxError: unexpected character after line continuation character
Perhaps you wanted a generator expression:
>>> query = "".join(str(var) for var in xrange(9))
>>> query
'012345678'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With