简体   繁体   English

Python 无限循环 for else

[英]Python infinite loop with for else

I am writing a function to count primes.我正在编写一个函数来计算素数。 I try to use a for-break-else framework nested in a while loop.我尝试使用嵌套在 while 循环中的 for-break-else 框架。 However, I got an infinite loop.但是,我得到了一个无限循环。 I knew the else is not with the right indentation.我知道else没有正确的缩进。 After I moved else ahead and made it paralleled with for, the problem was solved.在我向前移动else并将其与for,平行后for,问题就解决了。 However, I feel difficult to understand why the else block's original place would give me the infinite loop.但是,我觉得很难理解为什么else块的原始位置会给我无限循环。 Can someone help me with that?有人可以帮我吗? Thanks.谢谢。

def count_primes(num):
    primes = [2]
    x = 3
    if num < 2:
        return 0
    else:
        while x <= num:
            for y in range(3,x,2):
                if x%y ==0:
                    x += 2
                    break #jump out the for loop
                else:
                    primes.append(x)
                    x +=2 
    return primes
                    

In your function, you initialised your variable x at 3 but in your for loop you defined your loop range to go from y = 3 to x = 3. You should remember that the range function range(a,b) goes from a to (b-1) .在您的函数中,您将变量 x 初始化为 3,但在 for 循环中,您将循环范围定义为从 y = 3 到 x = 3。您应该记住范围函数range(a,b)a 到 ( b-1) Thus your loop is trying to loop over 3 to 2, which is not possible, thus you never execute the code within.因此,您的循环试图循环 3 到 2,这是不可能的,因此您永远不会执行其中的代码。 That is why you have an infinite loop, because it always tries to run the loop, then cannot, then goes back to the while loop, without incrementing x.这就是为什么你有一个无限循环,因为它总是试图运行循环,然后不能,然后回到 while 循环,而不增加 x。

For the purpose of your code I would then initialize x at 5 for the loop to be executed:为了您的代码,我将在 5 处初始化 x 以执行循环:

def count_primes(num):
    primes = [2]
    x = 5
    if num < 2:
        return 0
    else:
        while x <= num:
            for y in range(3, x, 2):
                if x % y == 0:
                    x += 2
                    break  # jump out the for loop
                else:
                    primes.append(x)
                    x += 2
    return primes

But after testing, it is clear your code wouldn't give you a correct answer though.但是经过测试,很明显你的代码不会给你一个正确的答案。 Testing your function with num = 100 gives the result below, which is incorrect (21 for example is not a prime number):使用 num = 100 测试您的函数会给出以下结果,这是不正确的(例如 21 不是素数):

>>> count_primes(100)
[2, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129]

To keep with the logic you are trying to implement, here is another solution to return the list or primes:为了与您尝试实现的逻辑保持一致,这是返回列表或素数的另一种解决方案:

def count_primes(num):
    if num <= 1:
        return []

    primes = [2]
    x = 3
    while x <= num:
        is_prime = True
        for prime_numbers in primes:
            if x % prime_numbers == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(x)
        x += 2
    return primes

Testing it with num = 100 gives us the correct list of prime numbers below 100:用 num = 100 测试它会为我们提供 100 以下的正确素数列表:

>>> count_primes(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Python uses indentation to indicate a block of code. Python 使用缩进来表示代码块。 When else is with if, it gets fired everytime if is wrong.当 else 与 if 一起使用时,每次 if 错误时它都会被触发。 This increments value of x by x+=2.这将 x 的值增加 x+=2。 This increases the range of the loop everytime if statement is false, thus resulting in infinite loop.这会增加每次 if 语句为 false 时循环的范围,从而导致无限循环。 When else is paralled with for the x+=2 statement gets executed only when the for loop condition is false.当 else 与 for x+=2 并行时,仅当 for 循环条件为假时才会执行。

else:
primes.append(x)
x +=2 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM