For some reason, when the candidate number reaches 21, it realises 21 is divisible by 3, but then won’t break out of the for loop/ By contrast, for example for 25, is notes 25 is divisible by 5 then breaks out.
It seems specifically, when div == 3, it doesn’t break out of the loop. Why is this?
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.'
Here’s the output of the code:
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
A for loop is not a while loop.
In Python, the only type of for loop is what in other languages is ‘foreach’ – it iterates through a list of elements. In your case, you’re iterating through a range, ie a list of integers from 3 to y+2. It’s the number of elements in the list that determines when the iteration stops, not the value of any one of them. When you change
divwithin one iteration of the loop, that has no effect on the rest of the items.You can use
breakto break out of the loop if a condition is met. Or if you want to keep your logic, you could try usingwhileinstead, but then you’ll need to increment the counter manually.