Today our python built-in function is abs() which is useful for converting any type of number like complex, negative, integer and large to it’s absolute number. 

Need of abs() function in Python:

When we are doing some math work it is require to convert different types of numbers to their absolute value and do calculations. This abs() function will help us to convert different number bases, types to corresponding absolute values. These types of numbers bases include, real, positive, negative, binary, octal, hex etc.

Python abs() function syntax:

	abs(any-number)

From above syntax any-number can be a real, positive, negative, binary, octal, hex etc.

Examples: Let us start with abs() function with some examples and see how we can use them in Python coding.

Example1: Convert a real number to absolute number.

	>>> abs(23)
23

Example2: Convert a negative number to absolute number.

	>>> abs(-23)
23

Example3: Convert a positive number to absolute number.

	>>> abs(+23)
23

Example4: Convert a complex number to absolute number. To understand below example we should know how can we convert complex value to absolute value, have a look at khan academy tut for this. Below 1+2j absolute value is square root of 5.

	>>> abs(1+2j)
2.23606797749979

Example5: Convert a binary number to absolute number. In python binary numbers(base 2) are represented with 0b for example if you want to represent 0110 as binary number we have to use 0b0110 whose decimal value is 6. For example if we want absolute value of 0b010 use below example.

	>>> abs(0b010)
2

Example6: Convert a octal number to absolute number. In python octal numbers(base 8) are represented with 0 and followed with octal number. For example if you want to represent 72 as octal number we have to use 072 whose decimal value is 58. For example if we want absolute value of 0120 use below example.

	>>> abs(0120)
80

Example7: Convert a hex number to absolute number. In python hex numbers(base 16) are represented with 0x and followed with hex number. For example if you want to represent f8 as hex number we have to use 0xf8 whose decimal value is 248. For example if we want absolute value of 0x20 use below example.

	>>> abs(0x20)
32

Related functions: int()

Complete python built-in function list.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.