Prime


#1


Above this code I also have conditions so that if the number with which the function is called is less then 2 it returns False and if it equals 2, it return True. BUT, for me, the code that I ve inserted actually works, which I dont get. Given that the last line says return True, should the process be like: if the if condition is considered True (the remainer is 0), it returns False nad it keeps looping. At the end of the loop if it is returning False, shouldnt it return True in the end anyways, because after the loop ends, it says return True as the last line in the code?

I m not sure whether you understand me but the programme should execute a line of code after a line. So no matter what the result of the loop is, shouldnt it always be True in the end, because the last line in the code says to return True?

        n = 2
        while n < x:
            if x % n == 0:
                return False
            n += 1
        return True

#2

The last line is correct. It is the default return value if the loop completes iteration. Being as no False was returned during the loop, the only thing remaining is that the number must be prime.


#3

Sure, if no False was returned during the loop, it returns True. But even if False is returned, it continues the code, so it adds +1 to n and continues looping. If in the end of looping it returns False and the loop cant continue because the highest possible n has been reached, it continues to execute the next line of code which clearly says to return True. So my question is, isnt this block of code ALWAYS supposed to return True?


#4

This is not the case, at all. Nothing executes after return. The function is exited and ceases to run.


#5

Oh, I didnt know that. Thanks. U re the best!