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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With