Is_prime


#1

This is my code:

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

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


#2

why use x-1? the instructions say you need x-1, since you don't want to include x (otherwise the program wouldn't function) but range doesn't include x, so i don't see why you need -1 as well

for the rest, a function ends the moment a return keyword is reached, in your case in the first run of the loop, because either if is true, or else will run.

change the indention of else and return True so you get a for/else instead of a if/else

This way, True is only returned after the loop is finished running. Which means the number is indeed a prime.

I have a question, couldn't you find a similar topic to solve your problem? i answer this question multiply times a week


#3

I realized that else indentation was the problem so your first "else" needed to be moved back to be under "for" loop not under "if".


#4

Then don't answer his question.


#5

no? i was curious how users experience this. Not that i don't want to answer this


#8

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