Stuck on is_prime


#1



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


I am not able to find an error in the code! Please help!


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


#2

why x-1 in range? range does not include the stop value, so i don't see a reason to subtract one

a function ends the moment a return keyword is reached. If a return keyword is reached in a loop, the loop will break. In other words, your loop breaks in its first iteration, is this desired behavior?


#3

(post withdrawn by author, will be automatically deleted in 1 hour unless flagged)


#5

use for else, this way, true will be returned after the loop has finished running


#6

Thanks guys for suggestions! I corrected my code and it works well now!

def is_prime(x):
    if x<=1:
        return False

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

#7