Skip to main content
 首页 » 编程设计

python之如何在基于两个变量的单个语句中减少 if 和 elif with

2025年05月04日16JeffreyZhao

我们如何通过处理 c1 和 c2 不等于零来使所有内容都在单一 if 条件下

def func(self): 
        c1 = self.x.getc1() 
        c2 = self.x.getc2() 
 
        if c1 != 0: 
            cost = getcod(c1) 
            price = round(float(cost), 2) 
            return price 
        elif (c2 != 0): 
 
            cost = getcod(c2) 
            price = round(float(cost), 2) 
 
            return price 
        else: 
            return None 
 

请您参考如下方法:

使用 for 循环迭代这两个方法。

for m in [self.x.getc1, self.x.getc2]: 
    c = m() 
    if c != 0: 
        cost = getcod(c) 
        price = round(float(cost), 2) 
        return price 

如果循环终止而没有返回,None 将被隐式返回,或者您可以在循环后显式添加 return None。

与原来一样,第一个非零值将导致函数提前从循环内部返回。