gpt4 book ai didi

Python:在满足特定条件时跳过代码块(计算)而不使用 "if"语句

转载 作者:行者123 更新时间:2023-12-01 03:17:28 25 4
gpt4 key购买 nike

我有一小段代码,我正在尝试以更好的方式编写它,因为它有一堆“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]

最佳答案

确定每个步骤中将引发的错误,然后将这些异常添加到 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

关于Python:在满足特定条件时跳过代码块(计算)而不使用 "if"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com