Is_prime; what is the difference between these 2 codes?


#1



Hi everyone,

I've been stuck at this problem for a while now since I do not understand what the mistake is in my function (1) everytime I try the problem again I somehow come up with basically the same code. I looked through the forum and saw this code (2) which looks very similar to my own attempt. My question now is, in what way do (1) and (2) differ? "Return True" at the end in (1) is inside the for-loop whereas in (2) it is not but I cannot seem to understand the impact of this.

Thanks in advance

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


The code gives me an error at x = 2

(1)

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

is_prime

(2)

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

is_prime


#2

Your first example has an else branch on the if statement, so will return True for a lot of numbers that are not prime. Something will return on the first iteration of the loop, every time.

The second example is correct since it rejects divisible numbers but does not return anything else until the loop is complete. Be sure to call it by invoking the function...

is_prime(9)

#3

5 posts were split to a new topic: Difference between two functions


#4

Which code gives you the error at x=2? Code #2 or Code#1?


#5

i had same doubt too, my background is C++ and so i see the flow of conditional statements like this


#6

Ok, plz is it possible to explain the flow using the example of number 4,
lets take the number 4 and test if it is prime or not
Please can you explain with flow-steps.
like what will happen when n is 2, then when n is 3 ane tc etc...

The reason i ask is i come from a C++/C background, and i have a memmory of the syntax in that lang much simpler to understand, i am not sure why this one is not clear


#7

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