The objective of this Python post, you will see various Python examples that cover the following:
- What is abs() function?
- Python abs() function syntax and Parameters.
- Python abs() function examples.
What is abc() function?
Python abs() is a standard builtin python function, which is used to returns the absolute value of the given number. If the number is complex, the abs() method returns its magnitude.
Python absolute Syntax
Python abs() method syntax is the following.
abs(n)
Here, n is the required parameter, and it is the number.
The abs() method will returns the absolute value of the given number.
- For integers – absolute integer value is returned
- For floating numbers – floating absolute value is returned
- For complex numbers – the magnitude of the number is returned
See the first example of python abs() function following:
x = abs(-19.21) print(x)
Output
19.21
Python abs() function examples
1:Python abs() with complex number
y = abs(18 + 21j) print(y)
Output
27.65863337187866
2: Python abs() with different format numbers
x = 19.21e1/2 # exponential print(abs(x)) y = 0b1100 # binary print(abs(y)) z = 0o11 # octal print(abs(y)) w = 0xF # hexadecimal print(abs(w))
Output
86.05 12 12 15
3: Python absolute value of list
Let’s see take an example, how to obtain the absolute number from python list.
Assume, we have one lists, it has looks like:
inputList = [11, 2, -18, 50]
Also. use the map() and list() python function to convert it to the absolute value.
inputList = [11, 2, -18, 50] mappedList = map(abs, inputList) print(list(mappedList))
Output
[11, 2, 18, 50]
4: write a program to find out the absolute value of an input number in python
- Use a python input() function in your python program that allows the user to enter any number.
- Convert the user inputted number into absolute numbers using the abs () function.
- End of python program, Print the result
#program to find out absolute value of an input number in python num = int(input(" Please Enter the number : ")) abs = abs(num) print("The absolute value of given number is : ", abs)
Output
Please Enter the number : -5 The absolute value of given number is : 5