程序如何使用break语句控制

时间:2013-05-08 22:53:06

标签: python python-2.7 numpy python-3.x

有人可以解释这个程序和输出吗?我对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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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' 

答案 2 :(得分: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

答案 3 :(得分:0)

Break直接离开最内层的循环,然后转到外部for循环的下一步。