abs() Builtin Function

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

ParameterDescription
xA 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.

Python Program

x = -523
absVal = abs(x)
print(f'Absolute value of {x} is {absVal}.')
Run Code Copy

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 Copy

Output

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 Copy

Output

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

1. How do you find the absolute value of a number in Python?

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)
2. What does abs() function do in Python?

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)
3. what is the difference between fabs() and abs() functions in Python?

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)

Related Tutorials

Code copied to clipboard successfully 👍