Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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')
like image 707
wannik Avatar asked Aug 17 '15 07:08

wannik


1 Answers

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)

like image 153
Anand S Kumar Avatar answered Oct 03 '22 01:10

Anand S Kumar