Python - 确保变量保持正数 [英] Python - Ensuring a variable holds a positive number

查看:75
本文介绍了Python - 确保变量保持正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅的方法来确保给定的变量保持正值.

I am looking for an elegant way to ensure that a given variable remains positive.

我有两个保存正浮点数的变量,我根据某些条件将它们递减.最后我想保证我仍然有正数(或最多 0).伪代码如下所示:

I have two variables that hold positive float numbers and I decrement them according to certain conditions. At the end I want to guarantee that I still have positive numbers (or 0 at most). The pseudo code looks something like this:

list = [...]

value1 = N
value2 = M

for element in list:
    if ... :
        value1 -= X
    if ... :
        value2 -= Y

除了在末尾添加两个 ifs 之外,还有更优雅的解决方案吗?

Is there a more elegant solution than just adding two ifs at the end?

推荐答案

我不清楚你想做什么——变量可以是负数,也可以不是.

I am unclear as to what you want to do -- either the variables can be negative, or they can't.

  • 如果您要反复递减一个变量,并且在此之后您想检查它们是否为负,请使用 if 来执行 - 这就是它的用途!

  • If you are decrementing a variable repeatedly and after doing so you want to check whether they are negative, do so with an if -- that's what it's for!

if value < 0: # do stuff

  • 如果您认为变量应该永远不会是负数,并且您想在代码中的代码中断言这一事实​​,那么您可以

  • If you think the variables should never be negative and you want to assert this fact in the code in the code, you do

    assert value > 0
    

    如果条件不成立,可能会引发 AssertionError(当 Python 不在调试模式下运行时,assert 不会执行).

    which may raise an AssertionError if the condition doesn't hold (assert will not execute when Python is not run in debug mode).

    如果您希望变量在已减小到 0 以下时为 0,请执行

    If you want the variable to be 0 if it has been decreased below 0, do

    value = max(value, 0)
    

  • 如果您希望变量为负数而否定,请执行

  • If you want the variable to be negated if it is negative, do

    value = value if value > 0 else -value
    

    value = abs(value)
    

  • 这篇关于Python - 确保变量保持正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆