Is_prime help me ! spent 2 hours debugging but no hope


#1



hi everyone, I am a bit stuck here....how can you loop through every number in range before going into the else statment?


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.


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


#2

i tried a lot of ways but none of them work, can anyone point out which part i did wrong instead of giving me the code?


#3

the problem is that a function ends the moment a return keyword is reached.

If the return keyword is reached in a loop, the loop will break (so the function can end)

This is the part where you go wrong, do you want me to suggest (suggest, not code) how to improve this?


#4

absolutely! I definitely want to heard you suggestion in how to change the code so that the code will go through everything
!


#5

You know the conditions in order for a number to be a prime number?

So you want to check if the remainder of x divided by n equals zero. If so, return False (the loop will break, saving on iterations)

after the loop, return True (since if the finishes running the number is a prime number)

If you need more help, post an updated version of your code


#6

ok , I did a bit of changes and merely got a different error message

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

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


#7

the url is the same for everyone, please copy paste your code to the forum


#8

i don't know how to copy paste and still having all the white space so a screenshot works the best


#9

you don't need break keyword?

return True is still inside the loop? so the loop will break in its first iteration (either true or false will be returned)


#10

I had the same issue. The problem is the indentation, the final return True statement should be outside the for loop, so True is returned when all the above if evaluations fail. And you don't need the break statement.
Hope that helps :slight_smile:


#11

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

    return True

Thank you so much!


#12