我有这个小块代码,我试图写得更好,因为这个有一堆“if”语句。这是一些大项目的小代码。问题是:当代码运行时,函数“f”,“g”或/和“k”可以返回None或数字数据。每当返回None值时,必须跳过其余的计算,因为无法进行数学运算(在这些函数中发生)。我尝试使用TRY / CATCH方法重写代码,但无法使其工作。我试图避免“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 :(得分: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 :(得分: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
时,函数的其余部分被跳过,并且该函数中的计算结束。