Is prime


I have the following code:

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

When I Save and Submit code, I get the error message "Your function fails on is_prime(6). It returns true, when it should return false."
What is happening wrong?


I would personally first check if x is 2 or 3 before running the loop.

Your loop is a bad idea, why? Because the last value of your for loop (in case of is_prime(6) the last value of the for loop is 5), determines if it is a prime. 5 is a prime, so true gets returned. Each time the loop runs, result gets overwritten with True or False, which is why the last value count, what you actually want to do is:

for loop:
     if condition:
          return False
return True

this will return false if if is true for any of the values, return False (the number is not a prime), or return True it loops through all the values. A function ends when the return statement is reached, which is why it is important your if x == 2 or x == 3 is before the loop


3 posts were split to a new topic:


A post was split to a new topic: Code is not working