Practice makes perfect 6/15. Please explain


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/isprime?action=lesson_resume

The function returns None for is_prime(2). I don’t understand why.
This is the error message.
Your function fails on is_prime(2). It returns None when it should return True.

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


#2

well, None is the default returned by functions, so no returned keyword is reached

Why do you think this code should return True?


#3

Oh I understand now. The function should end with return. So what I should do is this

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

#4

yes, that should work, now for x=2 the loop is:

for n in range(2, 1):

so the loop won’t run, execute code after loop (return true)

To expand, i explained that functions return None by default, at the end of the function, so when you use a return keyword, the function will end when the return keyword is reached

so when you place return True inside the loop (like you had before), the loop would end in its first iterations, so then for x=9 true would have been returned, which ins incorrect.


#5

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