Python abs() Function returns the absolute (non-negative value) value of a number. For example, absolute value of -5 is 5 and absolute of 5 is also 5. In this guide, we will see how to use abs() function in Python with the help of examples.
Python abs() function works on?
The abs() function works on following numbers:
1. Integers, for example 6, -6, 1 etc.
2. Floating point numbers, for example 5.34, -1.44 etc
3. Complex numbers, for example 3+4j, 4+6j etc.
Python abs() example
# integer number num = -5 print('Absolute value of -5 is:', abs(num)) # floating number fnum = -1.45 print('Absolute value of 1.45 is:', abs(fnum))
Output:
Python abs() function for complex numbers example
When a complex number is passed as an argument to abs() function, it returns the magnitude of the complex number. The magnitude of a complex number a + bj is equal to √a2+b2.
# complex number cnum = 4 - 5j print('Absolute value of 4 - 5j is:', abs(cnum)) cnum2 = 3 + 4j print('Absolute value of 3 + 4j is:', abs(cnum2))
Output:
Leave a Reply