Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

Python
<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

1 solution

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900