Is_prime


#1



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


Oops, try again. Your function fails on is_prime(0). It returns None when it should return False.


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


#2

Tried to change it a bit now its :
to be more precise

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

But again it shows the following error:
Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.


#3

a function ends the moment a return keyword is reached

if a return keyword is reached in a loop, the loop needs to break so the function can end

so for x=9, the first case tested by your loop is 2. 9%2==0 is false, so else will return True, the loop and function ends

hold on, true should only be returned after the loop has finished running successfully (this is the condition for a number to a prime number)

place return True outside the loop


#4

Ohh Yeah, done.. Thanks a lot


#5

Hi Haeshal99

I did something similar at first (and had the same problem you did).
stetim94's comment about the function ending once something is returned helped a lot;

it felt a bit unsatisfying to me to have to make a 'special case' in the code for x==2
the issue is - when you say
for n in range(2, x):
we've told the program "don't consider 0 and 1 when looking for factors of the number 'x'....start your search at 2. (This is sensible)

But when x==2, the code will think it's found a factor.

You can get around this by adding another condition - reminding the code that we're only interested in factors that are smaller than x.

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


#6

but for x=2, we get the following:

for i in range(2,2):

which false, given the stop value needs to be higher then the start value to run (not higher then or equal to)

so then, you don't need i < x because the loop won't run for x=2 (condition is false), so True will be returned

you also don't need break keyword, return will immediately end the function, the break keyword then never reached, so return keyword is pointless


#7

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

Your function fails on is_prime(-10). It returns True when it should return False.

What's the problem?


#9

negative numbers can't be prime number, instead of check x equals 1 or 2, simply check if x is lesser then 2, this will cover 0, 1 and all negative numbers


#10

Oh okay, thanks! @stetim94


#11

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