Search code examples
pythonvariablesnumbers

Python - Ensuring a variable holds a positive number


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

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

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


Solution

  • I am unclear as to what you want to do; numeric variables are either negative or not (never both).

    • 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
      

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

    • 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
      

      or

      value = abs(value)