2017-02-20 102 views
1

我有这个小块代码,我试图写更好的方法,因为这个代码有一堆“if”语句。这是一些大项目的小代码。问题是这样的:当代码运行时,函数“f”,“g”或/和“k”可以返回无或数字数据。无论何时返回None值,其余的计算必须被跳过,因为数学运算(发生在那些函数中)不能完成。我尝试使用TRY/CATCH方法重写代码,但无法使其工作。我试图避免“if”语句并重写简洁的方式。我很感激帮助。Python:在不使用“if”语句的情况下满足某些条件时跳过一段代码(计算)


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] 
+0

什么没有尝试/除了方法的工作? (我假设你的意思是你有f,g和k抛出一个异常而不是返回None,并且在except块中放置'[Q,A,output] = [None,None,None]?) – KernelPanic

+0

你可以'标准化'功能签名,然后让它们通过简单的中间检查一个接一个地执行,但在你的情况下,简单的尝试/除了应该足够多 - 只需让你的函数产生一个特定的异常,然后让你的代码线性执行并环绕它带有try/except块来捕获'非标准'返回值(例如,如果任何函数返回'None') – zwer

回答

1

确定将在每个步骤中被升高的错误,那么这些例外添加到try..except。在这个玩具例子,他们都TypeError,但我会添加ValueError作为示范:

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 
1

我想我有一个解决办法:

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() 

还有if声明,但他们不会像您的原始代码那样混淆嵌套。

这使用了这样一个事实,即如果函数return中的函数的其余部分被跳过,并且该函数中的计算结束。

相关问题