Is prime


#1

def is_prime(x):
    if x==0 or x==1:
            return False
            print "not prime"
    elif x==2:
            return True
            print "prime"
    else:
        for n in (2,(x-1)):
            result=x%n
            if result==0:    
                return False
                print "not prime"
                break
            else:
                print "prime"
                return True
                
is_prime(9)

I don't see where i'm wrong...

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

Is_Prime returns noe
#2

i know this is lazy, but i just explained the same thing two minutes ago here, please read it, if you then have any further questions, you can ask them in this topic


#3

way If i return True outside my for loop, the result will not return True in any case...?


#4

It finally works:

def is_prime(x):
        if x<2:
                return False
        if x==2:
                return True
        result=[]    
        for n in range(2,x):
                print (x%n)
                result.append(x%n)
        print (result)
        myBool=True
        for i in result:
                if i ==0:
                        print ("not Prime")
                        myBool= False
        if myBool==False:
                print (False)
                return False
        else:
                print (True)
                return True

#5

Just a reminder. Anything after a return statement is not executed.


#6

yes, but inside loop only i think. In my case, it works well


#7

Not just a loop but anywhere in your program.


#8

why did you change your code so much? No need

anyway, if you add a function call with a print statement:

print is_prime(11)

you should see True be printed


#9

stetim94, i add those think in my code because i was supposing, would be more easy to store my results in variable outside the loop, and also use if condition (outside loop) to manage easily with "return" in both cases(if and else).
Surely it's possible to do shortly, but don't know how yet...


#10

i was answering to many is_prime questions at once. A good challenge for later to optimize the code.