6. is_prime


#1



is_prime


Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.


not very sure why it doesnt compute when prime is 3, havent been able to solve the problem in days


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


#2

Your function call requires one argument,


#3

why x-1 in range? range doesn't include the stop value (x), no need to also subtract one.

uhm.. i would the special cases first, and then the loop

In the loop, the moment a return keyword is reached, the function (thus the loop) ends. this currently happens in the first run of your loop (either if is true, or else will run). you only want to return True after the loop has finished running (hint: indention)


#5

sry ignore that part i was using it for testing but i removed it now and thats the error


#6

What's the error? Please may I see your updated code having followed @stetim94 's advice,

Also your else statement's indentation needs to be on the same indentation level as your for loop. :slight_smile:


#7

THE NEW CODE

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

THE NEW ERROR

Oops, try again. Your function fails on is_prime(9). It returns True when it should return False


#8

this problem is already covered in the answer provided?

here is help topic on how to make indention show on the forum:


#9

ive fixed the indentation


#10

on the forum yes, not in your code, you have an if/else statement, which means either one of these will run in the first iteration of the loop, in which case a return keyword is reached. But you only want to return True after the loop has finished running, not in the first iteration, you need to place return True outside the loop


#11

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

Oops, try again. Your function fails on is_prime(3). It returns None when it should return True.
same error


#12

why can't you simply realize that you need to move else/return True outside the for loop?


#13

shiz sry, i got it, i was 2 indentations in, then i was 1 indentation in, then it was correct :zipper_mouth:


#14