6. is_prime - Why does this code not work?


#1



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


I expected this code to work for the exercise:


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


It doesn't, though. The error message is "Your function fails on is_prime(2). It returns None when it should return True.". I tried being lazy and changing the code to:

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

But all that does is display the error message "Your function fails on is_prime(9). It returns True when it should return False."
I also tried adding "break" after each return, but that didn't work either.
Can someone explain?


#2

@sircommoner: I think I've mentioned this on the other topic but just to make sure, lets talk about it again.
The break statement has no effect if it comes after a return statement, considering they are both in the same scope, one followed by the other.
Your function fails because if a number such as 15 gets there, at the first iteration it will ask:

Your code: " Is 15 % 2 equal to zero?"
Compiler: "No"
Your code: "Okay, so I will skip the instructions from this if and check if there's an else .. Oh, there is! Let me execute it!"
Your code: "Oh, there's a return True ... but 15 isn't prime. Oh well, better follow the rules of this algorithm!"

First check all the elements from your range to see if any of them whose module is equal to zero exists, if not, return True, after your for loop.


#3

Since you have put both the if and else part inside the for loop, its only going to iterate only once. So try placing the else segment in the same indentation as the for loop. it should work.


#4

def is_prime(x):
    if x == 2:
        return True
    if x > 1:
        for i in range(2, x):
            if x % i == 0:
                return False  #When a return runs, the function ends. 
                                     #So when x == 9, for i == 2, x%i != 0, 
                                     #it goes to "else" directly.
                                     #Which returns True.
                                     #Then the function ends, it won't run for i == 3. 
                                     #So try not to have more than one return in a function.
            else:
                return True
    else:
        return False

#5

Try this-

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