Question

I have some question regarding the for-else loop in another for loop. So here is an example:

primelist = []
for p in range (2, x+1):
    print 'in first for'
    raw_input()
    for i in range(2, p):
        print 'in second for'
        if p%i == 0:
            print 'in if'
            raw_input()
            break
    else:
        print 'in else'
        raw_input()
        primelist = primelist + [p]
return primelist

As you see this is for determining the prime numbers and store them into a list so that they can be retrieved later. So my problem is with the first for loop. When I run the program, it enters like this: First FOR loop, ELSE, First FOR loop, Second FOR loop and so on. Why does it skip to ELSE the first time? Also if I ask for the 1000th number I get : 7919 with the

for i in range(2, p)

and 7907 with the

for i in range(2, p/2).

Why is that? Hope you will help me with this, but please do not give other methods for implementing the Prime Number algorithm!

Était-ce utile?

La solution

Python's range doesn't include the ending value.

range[start, end)

So, In the first iteration, value of p will be 2 and range(2, 2) is an empty list. That is why the else part is entered.

print range(2, 2)  # []
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top