6. is_prime. How to stop dividing by 0?


#1



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


I've already solved this exercise inefficiently using the Sieve of Erastothenes, but I'm trying again with the instructions provided. I think I'm 90% of the way there.

Whenever I run the code, I get:
"Oops, try again. Your function fails on is_prime(0). It returns None when it should return False. "

I think the code runs into trouble as it tries to divide by zero and results in 'None', can anyone help me out?

Thanks


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


#2

The simplest way is to return False for all values less than 2 at the start of the function.


#4

I've tried that, now I get

"Your function fails on is_prime(2). It returns None when it should return True."

def is_prime(x):
if x < 2:
return False
else:
for n in range(2, int(x - 1)):
etc
etc


#5

That means you're making progress.

In Python it's okay to write single line statements:

 if x < 2: return False

We do not need an else or elif after an if that returns.

if .... return...
for ....

Since we can assume all inputs will be positive integers, the range can be simplified to,

range(2, x)

Recall the top (upper bound) value of the range is excluded, so the range will in effect be 2 thru x-1.

We canot see enough of your code to determine the reason for the error, but make the touch-ups and repost your code so we can have another look.


#6

argh, sorry, actually meant to copy-paste this instead.

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

but I get "Oops, try again. Your function fails on is_prime(2). It returns None when it should return True."


#9

Did you read my reply above? It doesn't look like it.


#10

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