Convert negative to positive number in Python

How to convert negative to positive number in Python ?

This tutorial guides you on how to convert negative to positive number in Python programming language using built-in functions like abs() , max() and other options as well and which one is better.

Convert negative to positive number in Python

Python interpreter supports many built-in functions which can be used for this conversion.

Convert negative to positive number in Python

 

For example let’s say you have the number x = -5 or -5.9 which is negative number and wanted to convert to positive number. Then you have the following built-in functions to do this.

abs(x)

The built-in function abs(x) returns the absolute value of a number. The argument can be an integer or floating point number, it always convert the number to positive number as shown below.

>>> x = -5

>>> abs(x)
5

>>> x = -5.9

>>> abs(x)
5.9

max(arg1, arg2)

This built-in function returns the largest item of two or more arguments.

Let’s say the given number is x = -5 which is negative number. And if you wanted to convert this number to positive then max() can be used as a trick to achieve this as shown below.

>>> x = -5

>>> max(x,-x)
5

Other options

The following are the other simple options to convert negative to positive number i.e., by simply multiplying number by -1 or printing negation of the given number. The both cases works only if you know the given number is negative.

For example,

>>> x = -5

>>> x*-1
5

>>> -x
5

Conclusion

I would suggest to use abs(x) built-in function instead of max(arg1, arg2, *args[key]), because there is an overhead while you use max as you need to iterate and find the largest number. Hence, it is performs slower than the abs(x) function.

Therefore, prefer abs() over max() funtion.

That’s it. Hope it helped 🙂

You’ll also like:

References

guest
0 Comments
Inline Feedbacks
View all comments