Do I need break or return?

I’m wondering why in the answer there is no need to “break” after “if” loop and use “else” before “return True”. For example, I tried to replace “return” with “print” like this:

def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                print "False"
        print "True"
is_prime(9)

It prints one False and one True. As the last print is True, shouldn’t the returned value of is_prime(9) be True in the original code?

return signals the function is done, and returns (hands back) data to the function call. Thus there is no need for break

Consider,

print (is_prime(9))

The above will print None since there is no return value to print except what Python returns.

1 Like