Always returns none?


#1

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

My function always returns None instead of False or True

I’m not sure why I keep getting none because I have the return statements… are they indented/placed incorrectly?



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



#2

update

messed with the code and found a few things I’ve left out. Now my function seems to be failing on is_prime(9), though I can’t pinpoint why.

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

#3

Examine the following brute force approach I believe is implied in the exercise…

>>> def is_prime(x):
    if x < 2: return False
    for n in range(2, x):
        if not (x % n): return False
    return True

>>> is_prime(17)
True
>>> is_prime(0)
False
>>> is_prime(9)
False
>>> 

I hope at this point you understand the logical not.

x % n == 0    # True if no remainder

x % n         # True if is a remainder

not (x % n)   # True if no remainder

#4

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