Yandex

Python abs() Function – Get Absolute Value of a Number



Python abs() Function

The abs() function in Python returns the absolute value of a number.

Syntax

abs(number)

Parameters:

  • number – An integer, float, or a number that implements __abs__()

Returns:

  • The non-negative absolute value of the given number.

Example: Using abs() with Integers

print(abs(-5))
5

Example: Using abs() with Floats

print(abs(-3.14))
3.14

Use Case: Why is abs() Useful?

  • Helps in finding the distance between numbers
  • Commonly used in sorting, graphs, and measurements
  • Useful in mathematical functions like distance calculations

Handling Complex Numbers

print(abs(3 + 4j))
5.0

This is because abs() returns the magnitude of a complex number.

Common Mistakes

  • Passing a string will raise a TypeError
  • Only numerical types are supported unless a class implements __abs__()

Interview Tip

In coding interviews, abs() is often used in problems involving distances, differences, or comparisons.

Summary

  • abs() returns the absolute value
  • Supports int, float, and complex
  • Raises TypeError if the argument is not numeric

Practice Problem

Write a program that reads a number from the user and prints its absolute value.

num = float(input("Enter a number: "))
print("Absolute value is:", abs(num))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M