Is_prime indentation question


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


When I have my second "else" statement indented to align with the "if" statement, I was receiving an error message:
"Oops, try again. Your function fails on is_prime(2). It returns None when it should return True."

However, when I align the indentation of that "else" statement with the "for" statement, the code works.


I'm confused about that because I thought "else" statements need to be indented at the same level as their respective "if" statements.

Am I thinking about this incorrectly?


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

# this doesn't work
def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2,x-1):
            if x % n == 0:
                return False
            else:
                return True


#2

Else statements don't necessarily have to have the same indentation as their parent if statement. This is especially true when dealing with for loops. Since a loop ends the moment a return key is reached. we want the last return key to be outside the for loop. In order to do this, the else statement needs to be at a different indentation level as it's if statement parent.


#3

your thinking contains a little flaw (but very common, so don't worry)

if you have if/else, in the first iteration of your loop true or false is returned

By default a function returns None in the end, if we want to return something different, we can use the return keyword, the catch is that when a return keyword is reached, the function ends

in other words, with if/else your loop ends in the first iteration of your loop.

If we look at the condition for numbers to be a prime number, breaking the loop in its first iteration is not what we want.

if we have a for/else, else will run when the condition of the for loop becomes false

for x=2, we have:

for n in range(2,2-1):

which is false, so else is reached, returning true.

why do x-1? range does not include its stop value


#4

In the is_prime function, that else needs to match the for loop header, so that it executes only in the case where none of the n values divide evenly into x. The else connected with a for loop executes only if all iterations are allowed to complete without being interrupted by a break or a return.

See @stetim94's and @aquaphoenix17's explanation of the logic, above.


#5

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