由于某种原因,当候选人数达到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
答案 0 :(得分:4)
for循环不是while循环。
在Python中,唯一类型的for循环是其他语言中的'foreach' - 它遍历元素列表。在您的情况下,您将遍历范围,即从3到y + 2的整数列表。它是列表中确定迭代何时停止的元素数,而不是其中任何一个的值。当您在循环的一次迭代中更改div
时,这对其余项目没有影响。
如果满足条件,您可以使用break
突破循环。或者,如果您想保留逻辑,可以尝试使用while
,但是您需要手动递增计数器。
答案 1 :(得分:1)
您的代码中没有break
语句。
答案 2 :(得分:1)
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
例如。
答案 3 :(得分:1)
相比之下,例如对于25,则音符25可被5整除 爆发了。
不,它没有。它还运行div = 6的循环,但没有打印任何内容,因为if
条件都没有。您的for
循环会在每次迭代开始时设置索引,因此您的div=10*y
行完全没有意义。