Is_prime: error with my code?


#1

Error Message:

Your function fails on is_prime(0). \
It returns None when it should return False.

My code:

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

#2

you will need a if condition to check for numbers smaller then 2, since they are not covered by the loop, and are not prime numbers either. (for numbers smaller then 2, return false)

also, in your loop, why use x-1? you don't want to include x in the for loop i get that, but range() doesn't include the stop value (in this case x), no need to subtract one

also, a loop ends the moment a return keyword is reached, in your case in the first run of the loop (either if is true, or else will run)

change the indention of else, so that true is only returned after the loop has finished running


#3

Something's still wrong here:

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

#4

the if condition for numbers less then two, should be before the loop. i was hoping this wold make sense, since the for loop doesn't run for values less then 2.

a return keyword is still reached in the first run of the loop, only return True after the loop has finished running, since none of the numbers between 2 and x should have a remainder of zero for it to be a prime number (hint: indention)


#5

I still don't get this.

if the input is less than 2, it is not a prime, which should return False, but for all the numbers in the range that is evenly divisible, this also should be False. In what instance does a True occur?

My code:

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

This returns an error:

Your function fails on is_prime(4). It returns True when it should return False

#6

now the loop will never run, take a moment to think about the logic of your your program:

def is_prime(x):
   if x is less then two return false
   for loop to loop over number of two and and greater
     return false if the remainder is zero
  return true since none of the numbers between 2 and x has a remainder of zero
  so the number is a prime

above is the logic of the program in pseudo code

My hints are made to think about for a minute, it is still important you create the program, not me.


#7

Thank you for your kind help. It allowed me to understand and execute the code.


#8

you're welcome :slight_smile:


#9

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