Stuck on Practice Makes Perfect (is_prime)


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


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
    else:
        for n in range(2, x):
            if x % n == 0:
                return False
                break
            else:
                return True


#2

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


#3

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


#4

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


#5

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


#6

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


#7

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