Python abs() Function

Python abs() function is used to return the absolute value of a number.

It removes any negative sign in front of a number, making it positive.

Visual Representation of Python abs() function (Integer and floating-value)

Syntax

abs(n)

Parameters

n: It can be a integer, float or a complex number.

Return value

  1. For an integer or a float – returns the positive version of the number.
  2. For complex numbers – returns the magnitude of the complex number.

Example 1: Integer and floating-value

# Absolute value of a negative integer
print(abs(-5))

# Absolute value of a negative floating-point number
print(abs(-19.21))

# Absolute value of zero
print(abs(0))

Output

5
19.21
0

Example 2: Passing the complex number

Passing the complex number

print(abs(19 + 21j))

Output

28.319604517012593

Mathematically, the magnitude of a complex number a + bj is computed as:

a2+b2

Example 3: Time-Distance calculation 

# Define the speed (in meters per second)
speed = 10

# Define the distance (in meters)
distance = -100

# Calculate the time it takes to travel the distance at the given speed
# Use the abs() function to ensure that the distance is positive
time = abs(distance) / speed

print(time)

Output

10.0

That’s it.

1 thought on “Python abs() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.