6 is_prime - What's wrong w/ my code?


#1


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


Error msg: Your function fails on is_prime(9). It returns True when it should return False.


But to me it seems correct...


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


#2

       for i in range(2, x):
            print i
            if x%i == 0:
                return False
            else:
                return True

You have a print in this loop does it show you any number bigger than 2? If no examine it further because this is probably the source of your problem.


#3

Nothing got printed... I just don't see how can this possibly not work...


#4

Ok nothing is printed because the function is not called, just add the is_prime(9) to the bottom of your code.


#5

Seems like it only looped thru once and when 9%2 != 0 it returned False... How do I let it loop through the whole range?


#6

The problem is that both parts of your if/else statement have a return in it, so no matter what option your choose you'll leave in the first loop. One idea to fix this would be to only leave with false for the if part and if that did not happen after all the numbers in your range, than you return true.


#7

Still didn't work... Any alternative?


#8

Could you show the updated code?


#9

def is_prime(x):
    x = int(x)
    if x == 2:
        return True
    elif x < 2:
        return False
    else:
        i = x-1
        while i > 1:
            print i
            if x%i != 0:
                i += 1
                x%i
                return False
            else:
                return True

#10

Done! Here's the fix:

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

#11

A post was split to a new topic: 6. is_prime - What´s wrong with this code?


#13