Pime number


#1

What's wrong with my code?

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

#2

A function ends the moment a return keyword is reached. This currently happens in the first iteration of the loop (either if is true and will return False or else will return True), the loop will simply break

You only want to return True after the for loop has finished running, since then you determined that x is not divisible by all numbers between 2 (included) and x (excluded), which is the condition for a number to be a prime nuber


#3

still doesnt work :frowning:

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

#4

i was talking about your for loop:

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

which still needs improvement like i told you in my original answer

this:

    if x== 2:
        return True
    if x<2:
        return False

was fine, you didn't have to move it

I actually made the assumption you have a problem with is_prime(9), not? You didn't include your error message


#5

yeah exactly that is the error


#6

look:

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

look at how many times n is printed, only once. The loop only does one iteration. Now read my original answer again please.


#7

ah finally got it, identation error! thank you!


#8

indention is rather important in python since python relies on indention to tell what is indie a function/loop and so on


#9

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