2013-05-08 85 views
-1

有人可以解釋這個程序和輸出嗎?我對if語句表示懷疑。我無法理解break語句在此是如何工作的:程序如何控制break語句

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' 

輸出:

2 is a prime number 
3 is a prime number 
4 equals 2 * 2 
5 is a prime number 
6 equals 2 * 3 
7 is a prime number 
8 equals 2 * 4 
9 equals 3 * 3 
+3

請格式化代碼和輸出。併發布真正的代碼沒有.... – 2013-05-08 22:55:13

回答

1

break聲明退出循環,而不進入else條款。如果循環終止而未到達break,則將輸入else子句。換句話說,循環搜索可能的除數;如果它找到一個它打印它並使用break離開循環。如果沒有找到除數,則for循環終止「正常」,因此進入else子句(在其中打印出它已找到素數)。

1

我會添加一些意見:

for n in range(2, 10): #Loops from 2 to 9, inclusive. Call this Loop A. 
    for x in range(2, n): #Loops from 2 to n-1, inclusive. Call this Loop B. 
     if n % x == 0: #If n is divisible by x, execute the indented code 
      print n, 'equals', x, '*', n/x #print the discovered factorization 
      break #Break out of loop B, skipping the "else" statement 
    else: #If the loop terminates naturally (without a break) this will be executed 
     # loop fell through without finding a factor 
     print n, 'is a prime number' 
0

顯然,這個方案是試圖找出素數。一個素數,沒有任何因素(即當你用素數除以x時,總有餘數),除1(明顯!)和它本身之外。因此,我們需要測試從2(即不是1)到測試前的數字的每個數字,以確定它是否是我們測試編號的一個因子。

在運行該測試,步驟通過像這樣:

# S1 is a set of numbers, and we want to identify the prime numbers within it. 
S1 = [2, 3, 4, 5, 6, 7, 8, 9] 

# test a whether n is PRIME: 
for n in S1: 
    # if n/x has no remainder, then it is not prime 
    for x in range(2, n): 
     if... 
      I have NO REMAINDER, then x is a factor of n, and n is not prime 
      -----> can "BREAK" out of test, because n is clearly not PRIME 
      --> move on to next n, and test it 
     else: 
      test next x against n 
      if we find NO FACTORS, then n is PRIME 
0

分段直接離開最內層循環並進入外for循環的下一步驟。