python - 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 above code work? following works

>>> query="" >>> var in xrange(9): query+=str(var) ...  >>> query '012345678' >>>  

the ; allowed combine "small statements". expressions, print, , like. for loop, on other hand, compound statement. see 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 example, if more illustrate question, rewrite

query = ''.join(str(var) var in xrange(9)) 

or if really need exec multiline statement, can add \n between assignment , for loop (as did in place):

>>> exec("query=''\nfor var in xrange(9):\n\tquery+=str(var)\nprint query") 012345678 

but note work in exec, not in interactive shell directly:

>>> query=''\nfor var in xrange(9):\n\tquery+=str(var)\nprint query syntaxerror: unexpected character after line continuation character 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -