Prevent the return False from breaking the loop


#1

Again, I come looking for aid.

I’ve passed the exercise, but need some help better understanding why. Here is what I used to satisfy the prime number function.

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

I ran into great frustration trying to have the else as apart of the if statement within the for-loop. This is because the return False was breaking the loop and preventing the else from being executed. The solution was to attach the else statement to the first if statement.

The way I believe it to operate is to first check if x < 2, check the for-loop if x >= 2, then run the else portion of the if/else statement if previous conditions are not satisfied. I’m convinced the if/else doesn’t take precedent over the for-loop as the program works down through the block of the function. Why? I’m not entirely certain.

And is there anyway to prevent the return False from breaking the loop so it can be apart of the if/else within the for-loop?

Thank you very much,

MD


FAQ: Learn Python - Practice Makes Perfect - factorial FAQ: Learn Python - Practice Makes Perfect - is_prime
#2

There is no alternate or default action (else) in the if statement. Only take action (return False) if the condition is true (number is divisible).

As for using the else on the for statement, it should only be used if there is a break statement in the loop. In your code above, simply let the last line of the function return True. This will catch 2, and all other primes.


#3

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