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; 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 you think the variables should never be negative and you want to assert this fact in the code in the code, you do
which may raise an
AssertionErrorif the condition doesn’t hold (assertwill 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
If you want the variable to be negated if it is negative, do
or