Help with is_prime


#1



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

I cannot figure out what is wrong with the code?
This is the error message that I keep getting (with different numbers):


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


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


#2

Remove the else and set the return statement to match the indent of for.


#3

Why don't you need the two lines? My codes was similar to this and your solution worked for mine as well


#4

if ...:

else:

When the loop is inside the if branch it will not see the code in the else branch, only the values that fail the if condition will. The return from the loop will be None.

if x < 2: return False

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

return True

When there is no return inside the loop, it runs to completion and flow drops to the last line.


#5

Okay, got it , thankss!!


#7

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