【问题标题】:How the program has control with the break statement [closed]程序如何使用 break 语句进行控制[关闭]
【发布时间】:2013-05-08 22:53:06
【问题描述】:

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

【问题讨论】:

  • 请格式化代码并输出。并发布没有....的真实代码。

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


【解决方案1】:

我会添加一些 cmets:

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】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-10
        • 1970-01-01
        • 2013-08-20
        相关资源
        最近更新 更多