Is_prime


#1



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


For x=3, is_prime returns none instead of True

I understand that it is returning None because I have the return inside the while loop, but what I don'nt understand is how to remove them from the while loop. Thanks!


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


#2

Very risky code, this. At least with for we don't run the risk of an infinite loop. You got off lucky because the loop never runs, and even if it did, it would terminate on the first iteration since there is a default return.

If I say any more it will be giving away too much before you've had a chance to try some alternate approach on your own. Give it a try and let us know what you come up with.


#3

I already get that the code isn't running. I was already very aware that it wasn't running. My question was how do I fix the return commands to be outside of the for loop


#4

If I say any more it will be giving away too much before you've had a chance to try some alternate approach on your own. Give it a try and let us know what you come up with.


#5

I've spent at least 30 min. with it so far. The only headway I made came from changing around the different variables/numbers I used in the for and if statements. I changed the x-1 in "range(2,x-1)" to just x, and that atleast got the code to run. Changed the while back to a for as well. Highest number I could get to was nine, where it returned False when it should return True.
Updated code:

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


#6

Okay, you're making good headway. I was a little concerned about the while loop with no counter running inside. for is better in this case, for now.

Given that the range is (2, x), 2 won't enter the loop. That means we don't need the test for 2, the range already excludes it. Just let it fall to the bottom and return True.

if x < 2: return False
for ...
    # if code
return True

I can't tell whether the else is in the if statement or the for, but either way, it can go.

Remember to return False if x is divisible.


#8

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