Is_Prime


#1



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


My code is failing on Is_Prime(9), it's returning true instead of false. I can't seem to understand why.


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


#2

A common error made in this exercise is

    else:
        return True

This will be the return of any odd number handed to the function. We can do away with it, completely.

Just have your function return True as its last line.

Now considering 2, as this is a brute force approach the loop excludes it, so it will fall to the last line. That means these lines are not needed:

    elif x == 2:
        return True

And, as the first if statement returns something, an elif is not needed. Just go straight into the for loop.


#3

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