Is_prime


#1



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

The error is as follows: Your function fails on is_prime(3).returns none when it should return true.
Can someone please tell me where I am going wrong?


#2

I just changed the code to
def is_prime(x):
if x<2:
return False
elif x==2:
return True
else:
for n in range (2,x-1):
if x%n==0:
return False
else:
return True
This is working correctly. I would like to know how the difference is generated between for ..else and if...else??


#3

When using return inside the for statement, we wouldn't normally use else, only when break is used. The else clause then applies only when the loop is completed.

b = [1,2,3,4,5]
for a in b:
    if a == 0:
        break
else:
    print "a doesn't equal zero"
print "this prints all the time"

Run the code, then add a 0 to the list and run it again. Notice the difference? The break bypasses the else clause.

Python 3 version

b = [1,2,3,4,5]
for a in b:
    if a == 0:
        break
else:
    print ("a doesn't equal zero")
print ("this prints all the time")

#4

b = [1,2,3,4,5]
for a in b:
if a == 0:
break
else:
print "a doesn't equal zero"
print "this prints all the time"


#5

I understand this ,but how does it affect my code?


#6

I am a beginner and having a really toughtime understanding this.


#7

Does that mean you wish for me to explain the code you copied?


#8

It would be great if you could tell me why its not working for if else but working for for else in this particular context?


#9

The else is in the if statement, not at the conclusion of the for statement. Too much indentation.


#10

I duplicated your code above and couldn't get it to run. I removed your finale else, leaving only one indentation for the final 'return True' and it worked.