Python 3 – Number abs() Method
In Python programming, the abs() method is commonly used to return the absolute value of a given number. The absolute value is the distance a number is from zero on a number line, regardless of its sign. This method can be used with both positive and negative values.
Syntax
The syntax of the abs() method is as follows:
abs(x)
Here, “x” is a required parameter and can be any integer, float, or even a complex number.
Example
To help understand this method better, let’s work through some examples:
Example 1: abs() method with an integer
x = -25
print("The absolute value of x is:", abs(x))
Output:
The absolute value of x is: 25
Example 2: abs() method with a float
y = -43.67
print("The absolute value of y is:", abs(y))
Output:
The absolute value of y is: 43.67
Example 3: abs() method with a complex number
z = -8 + 6j
print("The absolute value of z is:", abs(z))
Output:
The absolute value of z is: 10.0
Conclusion
The abs() method in Python is a simple and versatile tool that can be used to calculate the absolute value of a given number, regardless of its sign. This method can be used with integers, floats, and even complex numbers. By using this function, you can easily calculate the absolute value of any number in your Python programs.