Python 程序如何使用break语句进行控制

Python 程序如何使用break语句进行控制,python,python-2.7,numpy,python-3.x,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

有人能解释一下这个程序和它的输出吗?我对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

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

我将添加一些注释:

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' 

显然,这个程序试图识别素数。一个素数,除了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

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

请格式化代码并输出。发布真实的代码,但没有…谢谢。这真的帮助我了解发生了什么。