Practice 6/15 (Primes)


#1

Hey guys…

So I am very new to all of this and currently teaching myself… I wrote code that seems to work when inputing any numbers in place of “x”… it will return True when a prime and False when not… but the lesson is not letting the code pass while throwing an error that “Your function fails on is_prime(0). It returns None when it should return False.”

What is the reason for this? My code is below (the print statement was just the last test I ran)::

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

print(is_prime(11))


#2

Sorry, the post got rid of my indents… hopefully this posts better:

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


print(is_prime(10))

#3

While you can still edit, peer into that post and see how the code sample was marked down.


#4

There is no else for this conditional, so the return will be None.

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

>>> is_prime(1)
>>> 
>>> print is_prime(1)
None
>>> 

#5

Thank you MTF! Added an else condition to return false that’s inline with the original if statement and the code runs perfect and passed. Thank you!


#6

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