6. is_prime


#1



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

When codecademy checks my function it fails at is_prime(9). I believe this is due to the fact that 9 % 2 == 1 and it decides that 9 is a prime number while its not.

I don't know how to force it to continue checking all the rest of the values up to 9.


def is_prime(x):
    if x > 1:
        for i in range(2, x + 1):
            if x % i == 0 and x != i:
                return False
            else:
                return True
    elif x < 0 or x == 0:
        return False 
    else: 
        return False


#2

your for loop will run only once, since in the first run of the loop, if is true, or else will run, either way, in the first run a return keyword is reached, which means your function ends.

You might want to put the else statement at the same indent level as for loop, this way, the for loop will run for all instances, if the number is not a prime number, if will evaluate to true, False will be returned, function ends.

Otherwise, all values for the for loop will run, since no return is reached, it will execute else.

Also, why do you have have range(2,x+1)? Why the plus one? It doesn't make sense, and neither does the x != i


#3

It checks every value up to the number since it excludes the second value entered and if i = the number then it will always be divisible without a remainder, even the primes. I guess it should work if I exclude both of them. I also tried doing range(2, x-1) and then excluded the x != i but then it stopped at is_prime(2) so i changed it back.
Once I moved the else statement back it worked so thank-you very much.


#4

it works now, that is good. I would do neither (x+1 or x-1), i would simple do range(2,x), but range(2,x-1) should also work. Because then if x >1 is true for 2, and then else should run. (do remove x != 1), and then you should also be able to take out your elif.

Just a optimization, most important is that it works, and you understand why it works