Is_prime: logic


#1



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


I don't understand why the reasoning is wrong for is_prime(9).
it should return False: 9%3==0 --> FALSE --> Break


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


#2

If a return statement is reached the function exits.

If x%n is not 0 for just one n, True will be returned. That should only happen when x%n is not equal to 0 for all n < x.


#3
        if x%n==0:
            return False
            break

We want to return False as soon as x%n==0
else:
return True
if x%n never equals 0 then we want to return True
Isn't it the reasoning?


#4

I mixed up False and True in my answer, sorry. The problem is the else part. I editet my origial answer to make it more clear.


#5

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