Why does it throw such errors?


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

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

and when i change that None to False it shows
output 2:
Your function fails on is_prime(0). It returns None when it should return False.


#2

None is the default value returned by a function, so it indicates no return keyword is reached in your program

why is this? Well, if x=0, the for loop condition evaluates to false, so the loop won’t run. So the if condition which should check if x is zero is never reached. You should do this before the loop


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

then too i am getting the same error


#4

so if i run the latest version of your code, i will get this error:

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

are you 100% sure?


#5

oops didnt see that.
it says on is_prime(1).


#6

I guess the whole code is wrong.it shows composite only when the remainder is zero.Even for composite numbers like 45 it shows prime.Will write a new code again.
Thanks and sorry :slight_smile:


#7

I would try to fix the code, fixing gives more insights


#8

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