Prime is


#1

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

The error message is :
Oops, try again. Your function fails on is_prime(3). It returns False when it should return True.

I have this error with all numbers, divisible by 3.

def is_prime(x):
    if x > 2:
        for n in range(2,(x-1)):
            if x % n != 0:
                return True
            else:
                return False
                
    if x == 2:
        return True            
    else:
        return False
   
print is_prime(9)


#2

return causes a function to end, if a return keyword is reached in the loop, the loop breaks

Place return True outside the loop


#3

I am sorry but i don't understand where to place return, I don't know where should i place "return" and what to put in place of return if i remove it.

sorry for being silly


#4

in order for a number to be a prime number, x should not be divisible by all numbers between 2 (included) and x (excluded), this makes sense right?

Then the other thing we need to realize, is that a function ends the moment a return keyword is reached. Thus, we want to place return True after the for loop, not inside the for loop


#5

I tried to replace the "return" with the answer and after all the funtion return the answer, but it doesn't work either

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

   
print is_prime(13)

#6

but now answer will only hold True or False depending on the last iteration of the loop. That not how you determine if a number is a prime number.

You want to create a loop in which if x is divisible by any number between 2 and x, that the loop returns false.

There shouldn't be true inside the for loop


#7

Is this part is correct now?

    if x > 2:
        ret = 0
        for n in range(2, x-1):
            if x % n == 0:
                ret = False
            else:
                ret = True
                return ret

#8

no, true is still inside the loop.

true is part of else, so else should be place outside the for loop


#9

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