我有这个小块代码,我试图写更好的方法,因为这个代码有一堆“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]
什么没有尝试/除了方法的工作? (我假设你的意思是你有f,g和k抛出一个异常而不是返回None,并且在except块中放置'[Q,A,output] = [None,None,None]?) – KernelPanic
你可以'标准化'功能签名,然后让它们通过简单的中间检查一个接一个地执行,但在你的情况下,简单的尝试/除了应该足够多 - 只需让你的函数产生一个特定的异常,然后让你的代码线性执行并环绕它带有try/except块来捕获'非标准'返回值(例如,如果任何函数返回'None') – zwer