Contents
Python – abs()
Python abs() builtin function is used to find the absolute value of a given number.
In this tutorial, you will learn the syntax of abs() function, and then its usage with the help of example programs.
Syntax
The syntax of abs() function is
abs(x)
where
Parameter | Description |
---|---|
x | A number, or expression that evaluates to a number. |
Examples
1. Absolute value of a number
In this example, we will find the absolute value of a negative number.
Output
Absolute value of -523 is 523.
2. Absolute value of numeric expression
In this example, we will pass an expression to the abs() function, where the expression evaluates to a numeric value. abs() returns the absolute value of the expression’s resulting value.
Python Program
a = -523
b = 451
absVal = abs(a+b)
print(f'Absolute value of the expression (a+b) is {absVal}.')
Run Code CopyOutput
Absolute value of the expression (a+b) is 72.
3. Absolute value of a string – TypeError
If we provide an argument of any non-numeric type like string, abs() function raises TypeError.
Python Program
x = 'hello'
absVal = abs(x)
print(f'Absolute value of {x} is {absVal}.')
Run Code CopyOutput
Traceback (most recent call last):
File "example1.py", line 2, in <module>
absVal = abs(x)
TypeError: bad operand type for abs(): 'str'
Summary
In this tutorial of Python Examples, we learned the syntax of abs() function, and how to find the absolute value of a number or a numeric expression using abs() function with examples.
Frequently Asked Questions
Answer:
To find the absolute value of a number in Python, you can use abs() built-in function. Pass the given number as argument to the abs() built-in function and the function returns the absolute value of the given argument.
abs(-10.56)
Answer:
abs() is a built-in function in Python. abs() function finds the absolute value of the given argument and returns the resulting value.
abs(-8)
Answer:
fabs() always returns a floating point value irrespective of the type of given argument. Absolute function returns integer if the given argument is integer, or returns float type value if the given argument is float.
abs(-8)