Is_prime: function fails on is_prime(3)


#1



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


My error message is: Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.


I don't understand why it doesn't work. Please help me.


def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True

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


#2

why subtract one from x? range() doesn't include its stop value (its values lesser then (<) stop value, not lesser then or equal to (<=)), so i don't see a reason to subtract one


#3

Now I have just replaced x - 1 with x and it still doesn't work. In the error is now 9 instead of 3.


#4

a function ends the momnet a return keyword is reached

if a return keyword is reached in a loop, the loop will break

so your loop always breaks in your first iteration (For both prime and not prime numbers), is this the desired behavior?


#5

No, I need it to go through the whole code


#6

if the number is a prime number, the whole loop should run, when the loop has finished running (this only happens if false is not returned), true should be returned

so what should we do to overcome this problem?


#7

Print statements go a long way to finding out where the program behaves differently from what you intended


#9

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