Why does one code work for prime numbers, and the other doesn't?


#1

Hey all, I just finished the is_prime program in section 15, where you need to make a program to identify if a number is prime or not. I came up with a code that I could find no problem with, but it still wasn't working, and it only worked after changing the indentation and else clause of the last lines. So I'm just wondering why the original code doesn't work with what I had?

Original Code: 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

Revised Code: Works!

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

To me, it looks like they should behave the same way.
Thanks!


#2

Simply follow the sequence of events, to do so simply just add print statements to each section with different outputs so you know where it is in your program.

You have the tools to figure it out, so go ahead and give it a whack.

Example:

def is_prime(x):
    if x < 2:
        print("Number less than 2")
        return False
    else:
        print("Entering else statement")
        for n in range(2, (x - 1)):
            print("For Loop Iteration: %s" % (n + 1))
            if (x % n) == 0:
                print("Entering if statement to return False")
                return False
            else:
                print("Entering else statement to return True")
                return True
    print("If we reached this we failed!")

Now run this.


#3

It may not be working in Codecademy's browser, but it works fine in an online python interpreter. So nothing wrong with your code except you have'nt cleaned up the indentation.


#4

It does not work correctly mind you do 2 as an example.


#5

Are you addressing this to me ? I just ran his first code segment in an online python session because I don't have python installed on my Win8 machine and I can't be bothered turning on my linux machine just to test this bit of code.


#6

You mean if 2 is the input parameter or do you mean the first bit of code is totally useless ?


#7

Did you throw your revised code into the interpreter and try 2 or 3?

It will quickly tell you what's up.

Also check out this post


#8

My answer was addressing his original statement which appeared that his code was not working at all.


#9

Ah OK, so 2 and 3 print the "If we reached this we failed!" string because they aren't in the for clause?

Is this because the range for 2 would be -1, and the range for 3 would be 0?