Python 没有跳出for循环

Python 没有跳出for循环,python,loops,for-loop,Python,Loops,For Loop,出于某种原因,当候选数字达到21时,它意识到21可被3整除,但随后不会跳出For循环/相反,例如25,是注释25可被5整除,然后跳出 具体来说,当div==3时,它似乎不会跳出循环。为什么会这样 for cand in range (3,100): if cand%2 != 0: if ((cand ==3) or (cand ==5) or (cand ==7) or (cand ==11) or (cand == 13)): print str

出于某种原因,当候选数字达到21时,它意识到21可被3整除,但随后不会跳出For循环/相反,例如25,是注释25可被5整除,然后跳出

具体来说,当div==3时,它似乎不会跳出循环。为什么会这样

for cand in range (3,100):
    if cand%2 != 0:
        if ((cand ==3) or (cand ==5) or (cand ==7) or (cand ==11) or (cand == 13)):
            print str(cand) + ' is prime.'
        else:
            x = sqrt(cand)
            y= int (x)
            for div in range(3, (y+2)):
                if (cand%div == 0):
                    print div
                    print str(cand) + ' is divisible by' + str(div)
                    div = 10*y
                elif (div == y):
                    print str(cand) + ' is prime.'
下面是代码的输出:

3 is prime.
5 is prime.
7 is prime.
3
9 is divisible by3
11 is prime.
13 is prime.
3
15 is divisible by3
17 is prime.
19 is prime.
3
21 is divisible by3
21 is prime.
23 is prime.
5
25 is divisible by5
3
27 is divisible by3
27 is prime.
29 is prime.
31 is prime.
3
33 is divisible by3
33 is prime.
5
35 is divisible by5
37 is prime.
3
39 is divisible by3
39 is prime.
41 is prime.
43 is prime.
3
45 is divisible by3
5
45 is divisible by5
45 is prime.
47 is prime.
7
49 is divisible by7
3
51 is divisible by3
51 is prime.
53 is prime.
5
55 is divisible by5
55 is prime.
3
57 is divisible by3
57 is prime.
59 is prime.
61 is prime.
3
63 is divisible by3
7
63 is divisible by7
5
65 is divisible by5
65 is prime.
67 is prime.
3
69 is divisible by3
69 is prime.
71 is prime.
73 is prime.
3
75 is divisible by3
5
75 is divisible by5
75 is prime.
7
77 is divisible by7
77 is prime.
79 is prime.
3
81 is divisible by3
9
81 is divisible by9
83 is prime.
5
85 is divisible by5
85 is prime.
3
87 is divisible by3
87 is prime.
89 is prime.
7
91 is divisible by7
91 is prime.
3
93 is divisible by3
93 is prime.
5
95 is divisible by5
95 is prime.
97 is prime.
3
99 is divisible by3
9
99 is divisible by9

您的代码中没有
break
语句。

for循环不是while循环

在Python中,for循环的唯一类型是其他语言中的“foreach”——它遍历元素列表。在您的例子中,您正在迭代一个范围,即从3到y+2的整数列表。决定迭代何时停止的是列表中元素的数量,而不是其中任何一个元素的值。在循环的一次迭代中更改
div
时,对其余项没有影响


如果满足条件,可以使用
break
中断循环。或者,如果您想保留逻辑,可以尝试使用
而不是
,但是您需要手动递增计数器。

Python循环不是这样工作的:

#!/usr/bin/env python
for a in range(1,20):
        print a
        a = 39
考虑:

for a in [32,14,"a",False]:
        print a
        a = True
比如说

相比之下,例如25,注释25可以被5整除吗 爆发了


不,没有。它还运行div=6的循环,但不会打印任何内容,因为if
条件都不成立。你的
for
循环在每次迭代开始时设置索引,因此你的
div=10*y
行完全没有意义。

我看不到
break
return
raise
。你希望它什么时候能跳出这两个for循环?为什么?所以,我在看第二个for循环。如果cand%div不产生余数,则div数将乘以10,因此根据我的扭曲逻辑,它不应再乘以范围3(y+2)。当div编号不是3时,这种逻辑似乎成立…@Ravin-python-for循环不是这样工作的。如果您想中断,请使用
break
ah真棒,谢谢!!好吧,这就解决了。好吧-所以一个中断可以解决问题(顺便说一句,谢谢),但是当div超出循环的范围时,循环不应该自动中断吗?@Ravin:你的两个循环都从3开始。为什么3会超出从3开始的范围?