14,241,806 members
Rate this:
See more:
I've tried two loops samples but ı didint understand why when"loop1" starts from "3", "loop2" starts from "2"? ı supposed that both should have been the same.

Here is the output:

3 prime
4 = 2 * 2.0
5 prime
2 prime
3 prime
4 = 2 * 2.0
5 prime

What I have tried:

`<pre lang="Python">`

```def loop1():
for n in range (2,6):
for x in range(2,n):
if n % x==0:
print(n,"=",x,"*",n/x)
else:
print(n,"prime")

break
loop1()

def loop2():
for c in range (2,6):
for k in range(2,c):
if c % k==0:
print(c,"=",k,"*",c/k)
break
else:
print(c,"prime")
loop2()```
Posted
Updated 4-Dec-18 2:58am

Rate this:

## Solution 1

The second loop tries to repeat for the range (2,2) in the first iteration. Which is effectively while `x` is greater than 2 and less than 2: but that is impossible so the loop terminates. So the output starts at 3 which is the next iteration of the outer loop when `n` has a value of 3.

If you look at the output from the second loop you can see the first line output is :
`2 prime`

But you know that 2 is not a prime so how did that happen? Simply because your `else` clause is only indented once so it belongs to the preceding `for` statement rather than the `if`.

Top Experts
Last 24hrsThis month
 Richard MacCutchan 105 OriginalGriff 80 #realJSOP 20 Afzaal Ahmad Zeeshan 10 raddevus 10
 OriginalGriff 4,794 Richard MacCutchan 1,408 Maciej Los 1,115 CPallini 904 MadMyche 879

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100