views:

303

answers:

4

How can I convert a negative number to positive in Python? (And keep that positive value.)

+11  A: 
>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

Don't forget to check the docs.

Roger Pate
[abs](http://docs.python.org/library/functions.html#abs)
Roger Pate
@Roger: add the link to the doc in the body of the answer instead? It took me a moment to realise that your comment had a link.
Manoj Govindan
`-n` is enlightening
dhill
+6  A: 

If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs():

>>> abs(-1)
1
>>> abs(1)
1
BoltClock
+4  A: 

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)
Tim
+2  A: 
In [6]: x = -2
In [7]: x
Out[7]: -2

In [8]: abs(x)
Out[8]: 2

Actually abs will return the absolute value of any number. Absolute value is always a non-negative number.

Tauquir
Does abs(0) return a positive number? :)
Roger Pate
in arithmetic, −0 = +0 = 0.
Tauquir