The Wayback Machine - https://web.archive.org/web/20240711201233/https://www.geeksforgeeks.org/abs-in-python/
Open In App

abs() in Python

Last Updated : 30 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Python abs() function return the absolute value. The absolute value of any number is always positive it removes the negative sign of a number in Python. 

Example:

Input: -29
Output: 29

Python abs() Function Syntax

The abs() function in Python has the following syntax:

Syntax: abs(number)

  • number: Integer, floating-point number, complex number.

Return: Returns the absolute value.

Python abs() Function Example

Let us see a few examples of the abs() function in Python.

abs() Function with an Integer Argument

In this example, we will pass an Integer value as an argument to the abs() function in Python and print its value to see how it works.

Python3




# An integer
var = -94
print('Absolute value of integer is:', abs(var))


Output:

Absolute value of integer is: 94

abs() Function with a Floating-Point Number

In this example, we will pass a float data into the abs() function and it will return an absolute value.

Python3




# floating point number
float_number = -54.26
print('Absolute value of float is:',
                  abs(float_number))


Output: 

Absolute value of float is: 54.26

abs() Function with a Complex Number

In this example, we will pass Python complex number into the abs() function and it will return an absolute value.

Python3




# A complex number
complex_number = (3 - 4j)
print('Absolute value or Magnitude of complex is:', abs(complex_number))


Output: 

Absolute value or Magnitude of complex is: 5.0

Time-Distance calculation using Python abs() Function

In this example, the equation shows the relationship between speed, distance traveled, and time taken by an object. We know that speed, time, and distance are never negative. Hence we will use the abs() method to calculate the exact time, distance, and speed.

Formula used:  

  • Distance  = Speed * Time
  • Time = Distance / Speed
  • Speed = Distance / Time

We declared 3 functions to calculate speed, distance, and time. Then passed the positive and negative integer and float point values to them using the Python abs() function. The abs() function will automatically convert the negative values to positive values, which will be used to calculate speed, distance, and time.

Python3




# Function to calculate speed
def cal_speed(dist, time):
    print(" Distance(km) :", dist)
    print(" Time(hr) :", time)
    return dist / time
 
# Function to calculate distance traveled
def cal_dis(speed, time):
    print(" Time(hr) :", time)
    print(" Speed(km / hr) :", speed)
    return speed * time
 
# Function to calculate time taken
def cal_time(dist, speed):
    print(" Distance(km) :", dist)
    print(" Speed(km / hr) :", speed)
    return speed * dist
 
 
# Driver Code
# Calling function cal_speed()
print(" The calculated Speed(km / hr) is :",
      cal_speed(abs(45.9), abs(-2)))
print("")
 
# Calling function cal_dis()
print(" The calculated Distance(km) :",
      cal_dis(abs(-62.9), abs(2.5)))
print("")
 
# Calling function cal_time()
print(" The calculated Time(hr) :",
      cal_time(abs(48.0), abs(4.5)))


Output:

 Distance(km) : 45.9
 Time(hr) : 2
 The calculated Speed(km / hr) is : 22.95

 Time(hr) : 2.5
 Speed(km / hr) : 62.9
 The calculated Distance(km) : 157.25

 Distance(km) : 48.0
 Speed(km / hr) : 4.5
 The calculated Time(hr) : 216.0


Previous Article
Next Article

Similar Reads

Python | fabs() vs abs()
Both the abs() and the fabs() function is used to find the absolute value of a number, i.e., remove the negative sign of a number. Syntax of abs(): abs(number) Syntax of fabs(): math.fabs(number) Both will return the absolute value of a number. The difference is that math.fabs(number) will always return a floating-point number even if the argument
2 min read
Python | Pandas Series.abs()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Series.abs() method is used to get the absolute numeric value of each element in Series/DataFrame. Syntax: Series.abs()Parameters:
1 min read
Python | Pandas DataFrame.abs()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.dataframe.abs() is one of the simplest pandas dataframe function. It returns an object with absolute value taken and it is only applicabl
2 min read
Python | Pandas Panel.abs()
In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data. Panel.abs() function is used to return a Series/DataFrame with absolute numeric value of each element. Sy
1 min read
Python - PyTorch abs() method
PyTorch torch.abs() method computes the element-wise absolute value of the given input tensor. Syntax: torch.abs(inp, out=None) ? Tensor Arguments inp: This is input tensor. out: This is optional parameter and is the output tensor. Return: It returns a Tensor having absolute value of input inp. Let's see this concept with the help of few examples:
1 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Practice Tags :
three90RightbarBannerImg