Skip to main content

Command Palette

Search for a command to run...

abs() function in Python

Updated
2 min read
abs() function in Python
A
Software Engineer at OpenText passionate about building scalable web applications and backend systems. I work mainly with Java, Spring Boot, Python, and modern web technologies. I enjoy creating things for the internet, exploring new tech, and sharing what I learn along the way.

Introduction

The abs() function returns the absolute value of a number. In case the number is a complex number, it returns its magnitude.

The syntax of the abs() function looks like this:

abs(n)

where n is the number whose absolute value has to be calculated. It can be:

  • an integer
  • a floating-point number
  • a complex number

Case 1: An Integer

In the case of an integer number as an argument, the abs() function returns its absolute value.

>>> abs(3)
3
>>> abs(-3)
3
>>>

Case 2: A Floating-Point Number

In the case of a floating-point number as an argument, the abs() function returns its absolute value.

>>> abs(3.2)
3.2
>>> abs(-3.2)
3.2
>>>

Case 3: A Complex Number

Complex numbers are the numbers that are expressed in the form of a+ib where, a,b are real numbers and ‘i’ is an imaginary number called “iota”. The value of i = (√-1).

In Python, a complex number is any number of the form a + bj, where a and b are real numbers, and j*j = -1.

In the case of a complex number as an argument, the abs() function returns its magnitude.

>>> abs(5 - 12j)
13.0
>>>

Conclusion

In this part, we learned about the Python abs() function with the help of examples.