6 - is prime


#1

I wrote two versions of code.

First:

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

Second:

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

what am I doing wrong?


#2

the first version of the code is better then the second. But both still share the same problem.

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.

Given return is the last thing a function does, when a return keyword is reached, the function ends

so your loop ends in the first iteration of the loop, which is not good for determining prime numbers.


#3

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