Is_prime


#1



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


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


I expected it to return False, but it returned True


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


#2

a function ends the moment a return keyword is reached

if a return keyword is reached in a loop, the loop breaks so the function can end

so, for x=9 the first number tested by your loop is 2. 9 % 2 == 0, which is false, so else runs, true is returned, function ends

you should return True after the loop, if the loop finishes running, the number is a prime number


#5

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