Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run multiline for loop in a single line

>>> 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'
>>> 
like image 776
Pankaj Singhal Avatar asked Jan 17 '26 06:01

Pankaj Singhal


2 Answers

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
like image 169
tobias_k Avatar answered Jan 19 '26 19:01

tobias_k


Perhaps you wanted a generator expression:

>>> query  = "".join(str(var) for var in xrange(9))
>>> query
'012345678'
like image 39
Kevin Avatar answered Jan 19 '26 20:01

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!