Python prime number function returning error in tutorial -
python newbie here, bear me...
unfortunately there's no "support" these tutorials, except posting questions in q&a forum , maybe student can help. know there ton of python prime functions out there, think i've come 1 works. however, codeacademy interpreter doesn't solution.
here challenge:
- define function called is_prime takes number x input.
- for each number n 2 x - 1, test if x evenly divisible n.
- if is, return false.
- if none of them are, return true.
here's solution (yes, know non-pythonic , super inelegant, i'm learning):
def is_prime(x): x = int(x) if x > 0: return false if x == 0: return false if x == 1: print "1 not prime number" return false if x == 2: print "2 prime" return true in range(2, x): #print if x % == 0: print "this not prime number" return false break else: print "this prime number" return true print is_prime(-10)
when run above in codeacademy interpreter, it's returning error:
oops, try again. function fails on is_prime(-10). returns true when should return false.
not sure how write conditional filter out negative integers, tried converting x integer , adding if x > 0: return false
doesn't seem work.
what doing wrong here?
you don't return result value greater 2.
for 0, 1 , 2, return it:
return true
for fourth case covers other numbers, print result, don't return boolean value.
edit: attempt filter negative values fails, because return false
when input positive, not negative:
if x > 0: return false
you should use instead:
if x < 0: return false
Comments
Post a Comment