Is_prime


#1



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


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


I don't understand why it fails on is_prime(0), since my condition states that if a number is smaller than 2 it should return False, that would mean numbers 0 and 1 should return False. However the errors says it returns None. And in the elif statement, what I understand is " if a number is greater than 2 then we test if it is divisible by n".
Please correct my understanding if i'm wrong. Thanks in advance!


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


#2

The loop will iterate exactly one time. Figure why?


#3

I didnt call the is_prime function? Not too sure...

Okay, so I only want the loop to happen for numbers 2 and above but based on my for condition, its only checking to see if the number is smaller than 2. is that why its only looping once?


#4

The main reason is because one of the branches will be followed, no matter what, and every branch leads to a return, which ends execution.


#5

ah ok i got it! so i have to place the return functions above the for. Thanks mtf!


#6

Where we place the return is by design, not by any special rule. It is a point in the function where control flow kicks a result back to the caller.

Eg.

def ...(x):
    if x < 2:
        return False

In the above, values less than 2 are rejected, so return False. We know that numbers less than 2 are not prime. It becomes a design constraint.


#7

A post was split to a new topic: Your function fails on is_prime(0)


#9

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