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:
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.
Example2: Convert a negative number to absolute number.
Example3: Convert a positive number to absolute number.
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.
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.
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.
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.
Related functions: int()
Latest posts by Surendra Anne (see all)
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018
- wget download a file to a directory in Linux/Unix - June 4, 2018
- GIT: How to compare two GIT branches? - June 3, 2018
- Online training on Linux Bash shell scripting - February 8, 2018