mercredi 25 mai 2016

Behavior of pass and break in multiple loop in Python

I'm very new to Python, and when following the tutorial, I decided to run a more complete script of factorization and prime number testing:

prim = []
comp = []
for i in range(2, 101):
  for n in range(2, i//2 + 1):
    if i % n == 0:
      if n <= i//n:
        print(i, 'is equal to', n, '*', i//n)
        if not i in comp:
          comp.append(i)
      else:
        break
  else:
    print(i, 'is a prime number')
    prim.append(i)

It is supposed to store the prime numbers and the composite numbers in lists called prim and comp respectively, prints xxx is a prime number for prime numbers, and prints only the unique factorization for composite numbers, such as:

30 is equal to 2 * 15
30 is equal to 3 * 10
30 is equal to 5 * 6

The code runs successfully and seems to work, but then I noticed that for square numbers of prime numbers (namely, 4, 9, 25, and 49), it is both factorized and shown as a prime number, which is clearly wrong. After a bit of trial and error, I came up with the following code:

prim = []
comp = []
for i in range(2, 101):
  for n in range(2, i//2 + 1):
    if i % n == 0:
      if n <= i//n:
        print(i, 'is equal to', n, '*', i//n)
        if not i in comp:
          comp.append(i)
      else:
        pass
      break
  else:
    print(i, 'is a prime number')
    prim.append(i)

And it now works correctly as intended. However, I understand neither why I got it wrong before nor how I got it right now. I know it has something to do with the level I use break, but as I'm just beginning to grasp the way Python syntax handles loops and flow controls, I'm not yet able to pinpoint the problem. Any thoughts would be appreciated.

Aucun commentaire:

Enregistrer un commentaire