Summary: in this tutorial, you’ll learn how to use the Python abs()
function to return an absolute value of a variable.
Introduction to the Python abs() function
The abs()
function returns an absolute value of a number. Here’s the syntax of the abs()
function:
abs(x)
Code language: Python (python)
In this syntax, x
can be an integer, a floating point number, or a complex number. If x
is a complex number, the abs()
returns the magnitude of that complex number.
Also, x
can be an object that implements the __abs__()
method. In this case, the abs()
function will delegate to the __abs__()
method.
Python abs() function example
Let’s take some examples of using the abs()
function.
1) Using abs() function with numbers
The following example uses the abs()
function with numbers:
balance = -10
print(abs(balance)) # 👉 10
owed_amount = -20.99
print(abs(owed_amount)) # 👉 20.99
c = 3 - 5j
print(abs(c)) # 👉 5.0
Code language: Python (python)
2) Using abs() function with a user-defined object
The following example creates a class Balance
that implements the __abs__()
method:
class Balance:
def __init__(self, amount):
self.amount = amount
def __abs__(self):
return abs(self.amount)
balance = Balance(-299)
print(abs(balance)) # 👉 -299
Code language: Python (python)
When we pass the balance
object to the abs()
function, the abs()
function delegates the call to the __abs__()
method that returns the absolute value of the amount
attribute.
Summary
- Use the Python
abs()
function to return the absolute value of a number or an object that implements the__abs__()
method.