首页 > 解决方案 > Python 公式创建

问题描述

我需要创建一个具有以下标准的公式。重量、数量、单位和价格都是浮动的。

公式有 4 个参数:重量、数量、单位、价格

IF Weight is 0 then (Quantity * Unit)/Price Then 如果上面的结果是 GT 或 LT 一个值返回X

IF Weight is not 0 then (Weight * Unit)/Price Then if the above result is GT or LT a value returnX

def CatchWeight(totCatchWgt, QtyShip, Unit, Extended):
    try:
        v_calc = 0
        if totCatchWgt == 0:
            v_calc = (QtyShip * Unit)/Extended
            if v_calc < 0.9 or v_calc > 1.111:
                return "X"
        elif (totCatchWgt < 0) | (totCatchWgt > 0):
            v_calc = (totCatchWgt * Unit)/Extended
            if v_calc < 0.9 or v_calc > 1.111:
                return "X"
    except ZeroDivisionError:
        pass

当前公式未正确检查 Weight = 0,并且无论X同一行上的 weight 是否为 0,两个 if 语句都将返回。

标签: python

解决方案


考虑使用这样的东西来获得更简洁的代码并实现您的目标。

def check_v_calc(v_calc):
    if v_calc < 0.9 or v_calc > 1.111:
        return "X"
    else:
        # should return some resonable value
        return "Y"

def CatchWeight(totCatchWgt, QtyShip, Unit, Extended):
    if Extended == 0:
        # only case when we will get ZeroDivisionError
        raise ZeroDivisionError('Extended parameter cannnot be zero!')
    if totCatchWgt == 0:
        v_calc = (QtyShip * Unit)/Extended
    else:
        v_calc = (totCatchWgt * Unit)/Extended
    return check_v_calc(v_calc)

推荐阅读