6. is_prime


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#

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

However in line 4 I put a condition that returns False if x < 2, so why is the function returning none when x == 0? Thanks.

def is_prime(x):
    x = int(x)
    for i in range(2, x-1):
        if x < 2:
            return False
        elif (x % i) == 0:
            return False
        else:
            return True


#2

This should be outside of the loop. The else is not needed, just return True.

Make this change, re-post your code (after testing) and we can review it some more to get to your answer.


#3

Thanks, I brought it outside of the loop but am still getting the same error message.

def is_prime(x):
    x = int(x)
    for i in range(2, x-1):
        if x < 2:
            return False
        elif (x % i) == 0:
            return False
    else:
        return True

#4

As expected. I like to work on one problem at a time, test, and continue.

There is no return statement separate from the loop, and the loop does not run if x==0, so the function returns None.

Remove the else and it will return True. Clearly we need to test for 0, or values less than 2.

if x < 2: return False

or we could raise a ValueError,

if x < 2: raise ValueError

but the SCT will not be able to pass the code if a console error occurs. Best to return False. It's important that this check be before the loop.

    if x < 2 or x % 2 == 0 and x != 2: return False
    if x > 2:
        for i in range(3, x):
            if x % i == 0: return False
    return True

The first line tests for both x less than 2, and x is even but not 2. No point checking an even number if we can rule it out without a loop.

The second line prevents 2 from entering the loop. It will default to True.

Inside the loop, we iterate over the range 3..x-1. i will never equal x (range excludes the top value), Only when the loop completes do we return True, never inside the loop.

Test in IDLE

>>> def is_prime(x):
    if x < 2 or x % 2 == 0 and x != 2: return False
    if x > 2:
        for i in range(3, x):
            if x % i == 0: return False
    return True

>>> is_prime(0)
False
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(9)
False
>>>

#5

Thanks, that was a very detailed answer! I was just wondering, why did the loop not run if x == 0? Is it because the range is now between 2 and -1 which is impossible or something? Also why must we return True outside of the loop?


#6

In your orginal loop, the range started at 2, so 0 didn't get into the loop, and fell through to the very end of the function, where None was returned.


#7

2 posts were split to a new topic: Dont know what to do with this


#8

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