Python 不应该';否则,在下面的代码中不能缩进
在下面的示例中,Python 不应该';否则,在下面的代码中不能缩进,python,Python,在下面的示例中,else是否应该缩进?我运行了代码,但它不起作用,但我缩进了它(else),它起作用了。我说的对吗?如果文档是错误的,那么如何将其作为bug报告给python文档人员 >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... br
else
是否应该缩进?我运行了代码,但它不起作用,但我缩进了它(else
),它起作用了。我说的对吗?如果文档是错误的,那么如何将其作为bug报告给python文档人员
>>> 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'
...
这是一个Python的
示例,用于。。。其他
它基本上是在for循环结束并正常终止后调用else
部分中的代码(无论如何都不会中断)请参见您链接的文档:
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:
循环语句可能有一个else子句;它在循环结束时执行
通过用尽列表(使用for)或当条件
变为false(while),但在循环因中断而终止时不会变为false
陈述下面的循环举例说明了这一点,它搜索
素数:
示例正在运行,缩进很好,请看这里:
# 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
通过以下规则与的第二个相关:
循环语句可能有一个else子句当循环通过耗尽列表(使用for)或当条件变为false(使用while)而终止时执行,但当循环通过break语句终止时不执行该命令
在本例中,这意味着如果第二个for(在第二行中)将完成运行,但永远不会运行break命令,则将调用else-仅当n%x==0
从不求值为TRUE
时
如果(n%x==0)
在任何一点中断都将被调用,则第二个for将停止,从第一个for开始的n
将增长1,(n=n+1),第二个for将再次调用,并使用新的n
否,因为一个for
循环也可以有一个else
套件。不久前,这个构造将它变成了“最奇怪的语言特性”问题(请参阅)