Problem in one testcase.code works for rest others


#1




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


give results properly for each case , inclusive of 9.


Replace this line with your code.


#2

the code is here :
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
else:
return True
print is_prime(9)


#3

Are you writing an else clause in the inner if statement?


#5

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
            else:
                return True

#6

Just as I suspected. The return True in the if statement, else clause is the problem.

9 % 2

skips to else: return True. That is the problem.

Remove the else: and slide the return True over to the edge of local scope.

def ...

    return True

This will catch anything that makes it through the full loop iteration, meaning it is Prime.


#7

Done ! :smiley:
i still didnt get why this happened ,but removing else and shifting return to indentation of for worked.


#8

Rather than try to explain, may I refer you to a topic from earlier this week where else is discussed at length.

https://discuss.codecademy.com/t/need-help-my-code-is-running-elsewhere-but-i-get-error/68002


#9

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