2013-05-08 106 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循环的下一步骤。