Python codecademy question about indentation/else/return

Gamerboy

Distinguished
Aug 13, 2010
36
0
18,580
So I'm going through the codecademy python course and one assignment is to create a function that can determine if a number is prime or not. I don't understand what the difference is between these two examples. The first one doesn't work but the second one does. I get this error message when I try to submit the first one:

Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.

I got past the lesson but I would like to have an understanding of why these two sections of code are different. Why doesn't it recognize the return after the final else in the first example? Thank you

#This one doesn't work

Code:
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 one does

Code:
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
    return True


 
Solution


yes, that how "return" works.

In your first one, it return too soon.

rgd1101

Don't
Moderator


need to put in a code block. also read the line #this else is not in the one that works
 

Gamerboy

Distinguished
Aug 13, 2010
36
0
18,580
Now I get another error when I get rid of the x-1.

Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.


C++:
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
 

Gamerboy

Distinguished
Aug 13, 2010
36
0
18,580
I understand why the second section in the OP works now. x = 3 bypasses the for loop entirely the way it was written.

That should check if 9 % 3 == 0 which would be true so it should return False. Am I missing something else?

 

Gamerboy

Distinguished
Aug 13, 2010
36
0
18,580
I got it. It makes sense now but my head was about to explode haha.

the else inside the for loop is executing the first time the if is false. The else should be associated with the for instead of the if.


Thanks a lot rgd1101
 

rgd1101

Don't
Moderator


You welcome, have fun.