Stuck on Practice Makes Perfect (is_prime)


My code fails on is_prime(9). Returns True when it is supposed to be False.

I expected it to work, Could you debug it for me?

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


Nevermind. Found the answer. Had to indent the else in the for/else part to get a proper answer.


do you also understand why this change of indent is very important?


i don't get why the change in indent is necessary. Could you please explain?


first for the faulty code, lets say x=9, then the first case for 9 which is tested is 2:

if 9 % 2 == 0

this is false, so now else will run, which returns True. The moment a return keyword is reached, a function ends. Even when in a loop, the loop will simply break.

so, with the faulty code, the loop always ends in its first iteration.

True should only be returned after the loop has finished running, when you have for/else, else will run when the loop condition becomes false (loop finishes running), if the number is not a prime number, at some point in the loop, False will be returned loop breaks and the function ends


Ahhh! Got it! Thanks for clarifying that. Cheers!


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