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.
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.
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
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
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.
>>> x = -5 >>> x*-1 5 >>> -x 5
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:
- Convert floating point number to fixed point in Python
- What is %matplotlib inline and how to use ?
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- Run a Jupyter Notebook .ipynb file from terminal or cmd prompt
- Amazon Linux AMI : apt-get command not found
- Linux: sudo: apt-get: command not found
- How to Start Stop Restart MariaDB on Linux OS ?
- Putty Fatal Error No supported authentication methods available
- Find which users belongs to a specific group in linux
- Embed HTML within IPython Notebook
- Build a Docker Image with a Dockerfile and Cloud Build in GCP?
- Extract numbers from a string in python
- Error: helm install unknown flag: –name
- Install Python 3 on Windows 10 machine
- Can I use multiple values.yaml files for Helm Chart ?
- TypeError: a bytes-like object is required, not ‘str’ – Python3