6 is_prime, indentation question


#1



Hi! I would like to understand the following situation:

My code receives the error:
"Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.";
But if i move the last "else" (lines 10 & 11) one indentation to the left, the code works!

Why the last "else" should not be aligned with the last "if"?

Thanks!


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


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


#2

This is over-indented. Back it off so it lines up with the for (that is, it is not inside the loop code block).


#3

if you align else with if, in the first run of the loop either if evaluates to true, or else gets executed, either way, in the first run of the loop, a return keyword is reached. The moment a return keyword is reached, the function (thus the loop inside the function) ends/stops.

however, if you put else on the same indent level as the for loop, the whole for loop run, and return False if the number is not a prime, otherwise, it will reach your else statement, and return True, since the number is a prime


#4

Thanks for your answer mtf!


#5

Thanks, now i get it!