6/15 is_prime, Why is not working?


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

I really don't know why this is not working. I need help. :confused:


#2

Hi,
This code won' work you need to first define x and then divide by the numbers.
I wrote this code below

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

Hope this will help
Regards


#3

I think your problem lies in that you are using x-1 in your range. The end value of range is exclusive, so it is ending the range two numbers below your x instead of 1. If you use range(2, x) I would think it will work.


#4

Thanks for your response,

The problem was I had to define a special condition for the number 2 since when you set a "range" the initial value and the final value as the same which I did (range(2,x-1)) will result in range(2,2) and this will return an empty range. That was the problem with my code. It won't work with the number 2 as entry....


#5

Same problem with number 3, because 3-1 =2, so the range(2,2) results in none. Thanks for your argument, I was going crazy! :smile:


#6

But why on earth this code says that 9 is True; if 3 is in range(2,8) and 9%3==0 ???


#7

I am having the same problem. Below is my code. It should work but it says:

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

Why is this so?

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

#8

Here, the else statement has been executed when the for loop checks 9 % 'each' == 0 ( as each = 2 at the start of your range). This statement is not true so python then executes the else statement and returns True.

To avoid this, make use of the for/else relationship which is described in the loops lesson (chap 17).
When the else statement is indented directly underneath the for loop ( instead of under the if statement in your code), it will only be executed if the for loop is not interrupted by a 'break' command. Namely, when not one single number from 2 to (x-1) divide x.