Is_prime Why should the else be outside the for loop?


#1

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096
My code is as follow, this works correctly. However, should I move the else on line 7 inside the for loop( line3) I get a prime(9) error. My question is why is the else supposed to be outside the for loop?

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

#2

because a function ends the moment a return keyword is reached? If you put else at the same indent level as if, in the first run of your loop the function would end. Which would cripple your is_prime function.

also, this line:

yada += 1

not needed. the for loop will increase the counter for you


#3

Hi everybody,

I was cheking the codes for this task and I figure that the best way is not to use looping (for or while) because it will not run for long numbers. The memory will not let.

Try this way and make a raw_input to use the function for big big numbers

def is_prime(x):
if x==1 or x==-1:
return False
elif x==2 or x==3 or x==5 or x==7:
return True
elif x%2==0 or x%3==0 or x%5==0 or x%7==0:
return False
else:
return True