2012-08-30 62 views
2

python tutorial是一個示例(下面複製),不應該縮進else?我跑了代碼,它沒有工作,但我縮進它(else),它的工作。是的,我說的對嗎?如果文檔是錯誤的,那麼我如何將它報告爲python doc球員的bug?不應該在下面的代碼中進行縮進

>>> 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

不可以,因爲'for'循環可以有'else'套件*以及*。 –

+1

這個構造使它成爲前段時間的「最奇怪的語言特徵」問題(參見http://stackoverflow.com/a/3690698/288875) –

回答

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語句終止時,它被執行。

在這個例子中,這意味着其他人會被稱爲如果第二對(在第二行)將完成運行,但絕不會運行中斷命令 - 只有當n % x == 0從未EVAL到TRUE

如果(n % x == 0)在任何點處斷裂將被稱爲第二對將停止,n從第一供將由1種,(N = N + 1),第二個用於將被一個新的n再次調用。

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: