6/15 Prime number checker


#1
def is_prime(x):
  if x == 0:
    return False 
  if x == 1:
    return False
  if x == 2:
    return True
  if x == 3:
    return True
  else:
    x = abs(x)
    for n in range(2, (x-1)):
      print x
      if ((x % n) == 0):
        return False		
    else:
      return True

This code seems to work but I am seeing an error when it attempts to check is_prime(-7) , any idea why?


#2

Checking for inequality takes out an entire range…

if x < 2: return False

That line is not needed and may removed.

No else required since the if has a return.

if x > 2:
    for n in range(2, x):
        if x % n == 0: return False
return True

#3

So much cleaner than what I had, thanks for your help!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.