Curiosity
Curiosity

Reputation: 139

Python: Skip a block of code (calculation) when certain condition is met without using "if" statements

I have this small block of code which I am trying to write better way since this one has a bunch of "if" statements. This is the small code of some big project. The problem is this: as the code runs, function "f", "g", or/and "k" can return None or numerical data. Whenever None value is returned, rest of the calculation has to get skipped since mathematical operations (which happens in those functions) cannot be done. I tried to rewrite the code using TRY/CATCH method, but couldn't make it work. I am trying to avoid "if" statements and rewrite concise way. I appreciate the help.


def f(output):
    #some code which computes output which be None or numerical
    return [output*1,2]
def g(Y):
    #some code which computes Y which be None or numerical
    return Y*3
def k(output):
  #some code which computes output which be None or numerical
  return output*4
def foutput():
  #some code which computes "value" which be None or numerical 
  value=2.0
  return 1.0*value


#####START
#some code
output=foutput()

if output is not None:
    print 'S1'
    [output,A]=f(output)
    if output is not None:
        print 'S2'
        [a,b,c,Y]=[1,2,3,k(output)]
        if Y is not None:
            print 'S3'
            A=g(Y)
        else:
            [Q,A,output]=[None,None,None]
    else:
        [Q,A,output]=[None,None,None]
else:
    [Q,A,output]=[None,None,None]

Upvotes: 4

Views: 9648

Answers (2)

Anonymous1847
Anonymous1847

Reputation: 2598

I think I have a solution:

def compute():
    if f() is not None: print 'S1'
    else: return
    if g() is not None: print 'S2'
    else: return
    if k() is not None: print 'S3'
    else: return

compute()

There are still if statements, but they aren't confusingly nested as in your original code.

This uses the fact that when you return from a function, the rest of the function is skipped and computation in that function ends.

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49330

Determine the error that would be raised in each step, then add those exceptions to a try..except. In this toy example, they're all TypeError, but I'll add ValueError as a demonstration:

def f(output):
    #some code which computes output which be None or numerical
    return [output*1,2]
def g(Y):
    #some code which computes Y which be None or numerical
    return Y*3
def k(output):
  #some code which computes output which be None or numerical
  return output*4
def foutput():
  #some code which computes "value" which be None or numerical 
  value=2.0
  return 1.0*value


output=foutput()

try:
    print 'S1'
    output, A = f(output)
    print 'S2'
    a, b, c, Y = 1, 2, 3, k(output)
    print 'S3'
    A = g(Y)
except (ValueError, TypeError):
    Q = A = output = None
else:
    Q = 'success' # if none of this fails, you might want a default value for Q

Upvotes: 1

Related Questions