6/15 is_prime, brain says nope


#1

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

Hello everybody,

I’m stuck on this exercise. So far, the code is working fine, the only problem is with calling is_prime(9), returning True instead of False.

If we put it in the function it would be “if 9 % n == 0” return False and for n=3 it is 0. So why isn’t it returning False? :face_with_raised_eyebrow:

Also, it’s messed up with 49, 69, 99 and everything else with ending on 9… :brain::bomb::anger:

Help/explanation much appreciated :penguin:

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

#2

Remove the else clause from inside the loop. End the function with return True.

The above is not needed, either. 2 will fall to the last line.


#3

Awesome! Thank you for the quick help! :slight_smile:
But what was the problem with the 9s? :thinking:


#4

9 is not divisible by 2 so the else: return True line was executed. That is why we have no else clause in the loop.


#5

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