wannik
wannik

Reputation: 12706

raising an exception in else part of a for loop in Python

Both of the following code give the same result. But I'm not sure where should I put the raise statement.

def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
  for __ in range(max_iteration):
    half = start + (stop - start)/2
    if abs(f(half)) < eps or half - start < eps:
      return half 
    if f(half) * f(start) > 0:
      start = half
    else:
      stop = half
  else:
    raise ValueError('Cannot find root in the given range')

Or

def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
  for __ in range(max_iteration):
    half = start + (stop - start)/2
    if abs(f(half)) < eps or half - start < eps:
      return half 
    if f(half) * f(start) > 0:
      start = half
    else:
      stop = half

  raise ValueError('Cannot find root in the given range')

Upvotes: 5

Views: 280

Answers (2)

holdenweb
holdenweb

Reputation: 37023

The else clause of a for loop will only run after the loop terminates normally (i.e. by completing, rather than by being terminated with a break statement). Since there is no break in your loop - the only exit is via the return statement - both examples will execute the raise statement if max_iterations is exceeded.

In the example you give there is little point in putting the raise statement in an else clause, though it should do no harm.

Upvotes: 5

Anand S Kumar
Anand S Kumar

Reputation: 90889

Both methods are same, because you do not have a break statement in your for loop.

In the for..else construct, the else part is executed if the loop is exited without calling the break statement, if the loop gets exited using a break statement, the else part is not executed, since your loop does not have any break statement in it, both methods are similar as the else would always get executed.

Given that, I think if you always want to raise a ValueError if the loop does not return anything, then the second method looks better since its more readable and conveys what exactly you are trying to do. It would take a bit more effort to understand that if the loop gets exited the ValueError would be raised, if you use the first part (and using else there does not really make sense)

Upvotes: 5

Related Questions