6 is_prime question about for/else


#1

Hi guys,

I get that this is the solution that works but I do not understand why it is correct. I do not understand why the else statement is not executed. From previous tasks I learnt that in a for/else loop the else statement is always executed when the for loop ends given there is no break in it.

I did see answers about this task but no answer to my for/else question.

`def is_prime(x):
    if x<2:
        return False
    elif x==2:
        return True
    
    for n in range (2,x):
        if x%n==0:
            print "if was executed"  
            return False      
    else:
        print "Else was executed"
        return True `

Thanks,

Tim


#2

Since your loop has no break, you can just remove the else and deindent its body, perhaps then it makes sense to you.

Yes, the else in a loop-else is executed if the loop completed without being broken out of.