0

I wrote this to sort the prime numbers below 30.

p=[2]
i=2
while i<30:
    for x in p:
        if i%x==0:
            break
        else:
            p.append(i)
    i=i+1
print p

It gives me a long and duplicated result:

duplicated result

I noticed if I delete a tab in front of the 7th and 8th line then the code works fine. Why is that? Shouldn't 'if' and 'else' be in the same level?

Nuageux
  • 1,668
  • 1
  • 17
  • 29
range
  • 1
  • the problem seams to be that you only want to append if there is no remainder-less division for any element of p, not all the elements of p, for which the remainder is non-zero. – Chris May 12 '17 at 13:42
  • The [Python documentation](https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) shows an example just like this. – glibdud May 12 '17 at 13:45

0 Answers0