Is_prime


#1



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

Ooops try again, your code fails on is_prime(9).It returns True when it should return False

what's wrong with my code? Help Please!

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


#2

A function ends the moment a return keyword is reached, if a return keyword is reached in the loop, the loop simply breaks

So your loops breaks in the iteration (either true or false is returned)

when is it desired to return True?


#3

i think you shoud use for-else not if-else in last steps


#4

That is a possibility, but why do you need for/else?


#6

I think he means moving the else out of the for loop so it is an else statement to return True in the case that the if statement's condition is not satisfied.

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

#7

I know, but he says you should do something but not why, so i was curious for the why


#8

Ah, good point. I can't speak for him but my guess would be in order to make minimal changes to his code as he was very much on the right path.

Additionally it makes sense to use a for/else as if the function evaluated to the end of the third if, if x > 2 it would return nothing rather than True since it did indeed find a prime number.

I can see the other alternative to be using a boolean flag variable, initiating it as True, then flipping it to False if x % i == 0 evaluates to True. Then, at the end of the whole function, return the flag variable, that way there will always be something returned from the function.

A bit lengthy, but that is my take on it. Also, I understand this is probably an enrichment exercise for the OP and future readers rather than for your own sake. :smiley:


#9

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