【问题标题】:How to set a variable equal to zero based on a conditional if-then statement?如何根据条件 if-then 语句将变量设置为零?
【发布时间】:2019-12-03 21:31:30
【问题描述】:

我正在编写一个 Python 脚本 (IDLE) 来提出营养建议,公式如下:

potassium_recommendation = (73 + (yieldGoal * 0.21) + (soilPotassium * -0.565) + (yieldGoal * soilPotassium * -0.0016))

这个特定方程的输出告诉用户用户需要多少钾才能满足作物产量目标,稍后将用于计算需要施用的特定肥料量。

对于本例,假设 yieldGoal = 200,soilPotassium = 500。

如果您在生长季节开始时土壤钾含量高于作物从土壤中吸收的钾含量,则无需施肥。如果等式产生负数,您就会知道这种情况。

我想构建一个条件语句,如果达到负数,则将potassium_recommendation 变量设置为零。我怎样才能做到这一点?

这是我尝试过的:

potassium_recommendation = (73 + (200 * 0.21) + (500 * -0.565) + (200 * 500 * -0.0016))

        if potassium_recommendation < 0 == True:
            potassium_recommendation = 0
        else:
            potassium_recommendation = potassium_recommendation

print potassium_recommendation

当我运行这段代码时,它仍然会产生一个负数。我怎样才能使它为零?

【问题讨论】:

    标签: python if-statement conditional-statements


    【解决方案1】:

    删除 if 语句中的 '== True' 部分

    potassium_recommendation = (73 + (200 * 0.21) + (500 * -0.565) + (200 * 500 * -0.0016))
    if potassium_recommendation < 0:
        potassium_recommendation = 0
    
    print( potassium_recommendation)
    
    
    

    【讨论】:

      【解决方案2】:

      更紧凑的方法是使用math.max(MIN_VALUE, VALUE):

      potassium_recommendation = max(0, 73 + (200 * 0.21) + ...)
      

      【讨论】:

        【解决方案3】:

        你可以写potassium_recommendation &lt; 0,而不是potassium_recommendation &lt; 0 == True

        完整的代码如下所示:

        potassium_recommendation = (73 + (200 * 0.21) + (500 * -0.565) + (200 * 500 * -0.0016))
        
        if potassium_recommendation < 0:
          potassium_recommendation = 0
        
        print potassium_recommendation
        

        【讨论】:

          猜你喜欢
          • 2011-10-15
          • 1970-01-01
          • 2018-12-15
          • 2012-07-16
          • 1970-01-01
          • 2021-06-07
          • 1970-01-01
          • 2021-02-02
          • 1970-01-01
          相关资源
          最近更新 更多