-1

任何人都可以解释这个程序和输出吗?我对 if 语句有疑问。我无法理解 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
4

4 回答 4

2

我将添加一些评论:

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' 
于 2013-05-08T23:03:56.693 回答
1

break语句离开循环而不进入else子句。如果循环在没有到达 的情况下终止,则将进入break该子句。else换句话说,循环搜索可能的除数;如果找到它,它会打印它并使用break. 如果没有找到除数,则 for 循环“正常”终止并因此进入else子句(然后在该子句中打印它找到了一个素数)。

于 2013-05-08T23:02:56.960 回答
0

显然,这个程序试图识别素数。除了 1(显然!)和它本身之外,素数没有因子(即,当您将素数除以 x 时,总会有余数)。因此,我们需要测试从 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
于 2013-05-08T23:09:59.760 回答
0

Break 直接离开最内层循环,进入外层 for 循环的下一步。

于 2013-05-09T06:35:40.510 回答