15.6 - Is Prime - fails on "is_prime(1)"


#1


Oops, try again. Your function fails on is_prime(1). It returns True when it should return False.

Does not remove from possible values? Why is this code not satisfactory?

if picture doesn't show clearly...


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


#2

Move the return True line to outside of the loop.


#3

Thanks for the suggestion...when running the code as suggested, I was presented this error:

Oops, try again. Your code looks a bit off--it threw a "expected an indented block (python, line 6)" error. Check the Hint if you need help!


#4

Please repost your code. Thanks.


#5

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


#6

The else can be removed. It may still raise a possible error, but we can discuss that.


#7

Just removed the else line: newest error message:

Oops, try again. Your function crashed because you were trying to divide or modulo (%) by zero.


#8

Missing range, as in,

for n in range(2, x):

The list that range returns will not contain x.

Still possibly one more error to address. Try this and see.


#9

Oops, try again. Your function fails on is_prime(0). It returns None when it should return False.


#10

That was expected. Since 1 is not a Prime, and 0 is not a natural number, and primes as natural numbers cannot be negative we can exclude all values less than 2, before the loop.

if x < 2:
    return False

#11


#12

FINALLY!!!

Thanks for the assistance!


#13

Technically the else is not needed. Just return True outside of (after) the loop.


#14

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