Something is wrong with the section is_prime


#1



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


Ok. So I've been stuck on this for a while now, and just to get past it, I added the last two lines, which should literally make it impossible for is_prime(9) to return True. Yet would you look at the error that I get: Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.


Unless I'm incredibly stupid and missing something really obvious, this code should return False for is_prime(9). Please help.


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


#2

PYTHON uses indentation to mark begin and end of program sections.

Your program has 2 sections

def is_prime(n):
    #SECTION-1 the FOR-loop
    for i in range(2, n):
        if n % i == 0:
            return False
        else:
            return True
    #SECTION-2 the IF-ELIF-ELIF structure
    if n == 0 or n == 1:
        return False
    elif n == 2:
        return True
    elif n == 9:
        return False

As stands now the FOR-loop section will RESULT in a return
and thus EXITing the FUNCTION and will NEVER-EVER reach the SECTION-2....


#3

Thank you. This is very helpful.


#4

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