运行 单行多行for循环

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

为什么上面的代码不起作用?但是下面的作品

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

for 语句是复合语句,根据定义不能跟在分号后面

引用 python 文档

Compound statements

Compound statements consist of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

碰巧 for 语句是 Python

中的复合语句
compound_stmt ::=  if_stmt
                    | while_stmt
                    | for_stmt
                    | try_stmt
                    | with_stmt
                    | funcdef
                    | classdef
                    | decorated

所以不能跟在分号后面

绝大多数 Python 程序员只使用换行符来分隔语句,我怀疑大多数人甚至不知道分号是可能的。

并且(正如 Abhijit 所说)该功能是有限的:它仅适用于变量赋值和函数调用等简单语句,不适用于 "if"、"for"、[=16= 等控制语句],等等

也许您想要一个生成器表达式:

>>> query  = "".join(str(var) for var in xrange(9))
>>> query
'012345678'

;只允许组合"small statements"。那些是表达式、打印等。另一方面,for 循环是一个复合语句。见 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

在您的示例中,如果这不仅仅是为了说明您的问题,您可以将其重写为

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

或者如果你真的真的需要exec那个多行语句,你可以在赋值和for之间添加一个\n循环(就像你在另一个地方所做的那样):

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

但请注意,这仅在 exec 中有效,而不是直接在交互式 shell 中有效:

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