If you want to force a number to negative, regardless of whether it's initially positive or negative, you can use:
-abs(n)
Note that integer 0 will remain 0.
If you want to force a number to negative, regardless of whether it's initially positive or negative, you can use:
-abs(n)
Note that integer 0 will remain 0.
-abs(n) is a really good answer by Tom Karzes earlier because it works whether you know the number is negative or not.
If you know the number is a positive one though you can avoid the overhead of a function call by just taking the negative of the variable:
-n
This may not matter much at all, but if this code is in a hot loop like a gameloop then the overhead of the function call will add add up.
>>> timeit.timeit("x = -abs(y)", setup="y = 42", number=5000)
0.0005687898956239223
>>> timeit.timeit("x = -y", setup="y = 42", number=5000)
0.0002599889412522316
python - How to convert a negative number to positive? - Stack Overflow
python - Convert positive input into negative number - Stack Overflow
python - How the (-) operator converting negative numbers to positive works? - Stack Overflow
How to accept alternating positive and negative integers from user?
You want to negate it only if the start is greater than the end.
if start > end:
amount = -amount
Or you can tuck that right into the range() call:
for i in range(start, end, -amount if start > end else amount):
I am not sure this is what you really want, but to turn amount into a negataive number you can simply type this:
amount = amount * -1