How to compute a percentage increase/decrease multiplier in python without if statements

后端 未结 3 1777
渐次进展
渐次进展 2021-01-27 16:34

I have a scenario in which the user enter a positive, 0, or negative value which represents a percentage increase, no change, or percentage decrease, respectively. Example: 2.5

3条回答
  •  时光说笑
    2021-01-27 17:08

    if and else can actually be used in expressions on one line: x = a if b else c. You can't use elif, though, so you'll have to first refactor your code so it doesn't use them:

    if U == 0:
       multiplier = 1
    else:
        if U > 0:
           multiplier = U/100.0 + 1
        else:
           multiplier = (100 - (U * -1.0))/100.0
    

    This reduces to

    if U == 0:
       multiplier = 1
    else:
       multiplier = U/100.0 + 1 if U > 0 else (100 - (U * -1.0))/100.0
    

    Which reduces to

    multiplier = 1 if U == 0 else (U/100.0 + 1 if U > 0 else (100 - (U * -1.0))/100.0)
    

提交回复
热议问题