Each Answer to this Q is separated by one/two green lines.
How can I convert a negative number to positive in Python? (And keep a positive one.)
>>> n = -42 >>> -n # if you know n is negative 42 >>> abs(n) # for any n 42
Don’t forget to check the docs.
simply multiplying by -1 works in both ways …
>>> -10 * -1 10 >>> 10 * -1 -10
If “keep a positive one” means you want a positive number to stay positive, but also convert a negative number to positive, use
>>> abs(-1) 1 >>> abs(1) 1
The inbuilt function abs() would do the trick.
positivenum = abs(negativenum)
If you are working with numpy you can use
import numpy as np np.abs(-1.23) >> 1.23
It will provide absolute values.
In : x = -2 In : x Out: -2 In : abs(x) Out: 2
abs will return the
absolute value of any number. Absolute value is always a non-negative number.