6/15 Is_prime using another else after If


#1

Hi,

For the code I was using 2 ifs but whenever I use the else after my second if , the code gives out prime for 55.

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

is_prime(55)

It says that 55 is prime. I did remove the else and redefined the code to


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

But this works for 55 and any other number. I just want to understand that why my first code threw off the 55 as prime. Thank you :slight_smile:


#2

by default, a function returns None at the end of the function

if we want to return something else at the end of the function, we can use the return keyword

thus, when the return keyword is reached, the function ends

so in your first program, a return keyword is reached in the first iteration of your loop, so the function ends (the loop will break in order for the function to end)

so only the first value generated by range is tested

you can use else. but then for/else, not if/else like you did


#3

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