Table of Contents
In this tutorial, we will learn about the Python abs() function with the help of examples.
The abs()
function returns the absolute value of the given number. If the number is a complex number, abs()
returns its magnitude.
1. Example
number = -20 absolute_number = abs(number) print(absolute_number) # Output: 20
2. abs() Syntax
The syntax of abs()
method is:
abs(num)
3. abs() Parameters
abs()
method takes a single argument:
- num – a number whose absolute value is to be returned. The number can be:
- integer
- floating number
- complex number
4. abs() Return Value
abs()
method returns the absolute value of the given number.
- For integers – integer absolute value is returned
- For floating numbers – floating absolute value is returned
- For complex numbers – magnitude of the number is returned
5. Example 1: Get absolute value of a number
# random integer integer = -20 print('Absolute value of -20 is:', abs(integer)) #random floating number floating = -30.33 print('Absolute value of -30.33 is:', abs(floating))
Output
Absolute value of -20 is: 20 Absolute value of -30.33 is: 30.33
6. Example 2: Get magnitude of a complex number
# random complex number complex = (3 - 4j) print('Magnitude of 3 - 4j is:', abs(complex))
Output
Magnitude of 3 - 4j is: 5.0
Related posts:
Python Program to Convert Two Lists Into a Dictionary
Python Global Keyword
Python Program to Represent enum
Python Program to Find HCF or GCD
Python Package
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Function Arguments
Python String lower()
Python strptime()
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Copy a File
Python String swapcase()
Python input()
Python String isdigit()
Node.js vs Python for Backend Development
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Set issuperset()
Python Input, Output and Import
Python Modules
Python Program to Display Calendar
Python Program to Convert Kilometers to Miles
Python String casefold()
Python Matrices and NumPy Arrays
Python Directory and Files Management
Python iter()
Python timestamp to datetime and vice-versa
Python break and continue
Python Program to Swap Two Variables
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Find Sum of Natural Numbers Using Recursion
Python ord()
Deep Learning in Python - LazyProgrammer