Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
nmat Avatar asked Aug 19 '11 13:08

nmat


1 Answers

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

  • 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 not execute when Python is not 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)
    
like image 89
Katriel Avatar answered Nov 15 '22 10:11

Katriel