不应该在下面的代码中缩进

aWe*_*per 2 python

python教程中是一个例子(复制如下),不else应该缩进?我运行代码,它没有工作,但我缩进它(else),它工作.是的,我说的是对的吗?如果文档是错误的,那么如何将它作为bug报告给python doc人员?

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
...
Run Code Online (Sandbox Code Playgroud)

Abg*_*gan 7

查看您链接的文档:

Loop statements may have an else clause; it is executed when the loop 
terminates through exhaustion of the list (with for) or when the condition 
becomes false (with while), but not when the loop is terminated by a break 
statement. This is exemplified by the following loop, which searches for 
prime numbers:


Kuf*_*Kuf 7

Tha示例正在工作,缩进很好,看看这里:

                                                    # Ident level:
>>> for n in range(2, 10):                          # 0 
...     for x in range(2, n):                       # 1                          
...         if n % x == 0:                          # 2
...             print n, 'equals', x, '*', n/x      # 3
...             break                               # 3
...     else:                                       # 1
...         # loop fell through without finding a factor                        
...         print n, 'is a prime number'            # 2
Run Code Online (Sandbox Code Playgroud)

如您所见,通过遵循以下规则else与第二个相关for:

循环语句可能有一个else子句; 当循环通过列表耗尽(with for)或条件变为false(with while)时终止,但是当循环被break语句终止时,它被执行.

在该示例中,这意味着如果第二行(在第二行中)将完成运行但将永远不会运行break命令 - 只有在n % x == 0从不eval到的情况下才会调用else TRUE.

如果(n % x == 0)在任何时候中断将被调用,第二个将停止,n从第一个将增长1,(n = n + 1),第二个将再次调用new n.