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

时间:2012-08-30 10:35:56

标签: python

python tutorial中是一个例子(下面复制过),不应该缩进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'
...

3 个答案:

答案 0 :(得分: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:

答案 1 :(得分: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

如您所见,else遵循此规则与第二个for相关:

  

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

在示例中,这意味着如果第二行for(在第二行中)将完成运行但将永远不会运行break命令,则将调用else - 仅当n % x == 0从未计算到{{1}时}。

如果TRUE在任何时候中断将被调用,第二个将停止,(n % x == 0)从第一个for将增长1,(n = n + 1),第二个将是使用新的n再次调用。

答案 2 :(得分:0)

这是Python的for ... else http://psung.blogspot.co.il/2007/12/for-else-in-python.html

的示例

它基本上在for循环结束后调用else部分中的代码并正常终止(不以任何方式破坏)