Python abs()
The abs()
function is a built-in Python function that returns the absolute value of a number. The absolute value represents the distance of a number from zero on the number line, always resulting in a non-negative value. This function removes the negative sign from negative numbers while leaving positive numbers unchanged.
The abs()
function is commonly used in mathematical calculations, data analysis, distance calculations, and anywhere there is a need to work with magnitudes rather than signed values. It accepts integers, floating-point numbers, and complex numbers as input, making it versatile for various numerical operations.
Syntax
abs(number)
Parameters:
number
: The numeric value for which the absolute value is to be found. This can be an integer, floating-point number, or complex number.
Return value:
The abs()
function returns the absolute value of the given number:
- For integers and floating-point numbers: returns the positive magnitude
- For complex numbers: returns the magnitude (distance from origin)
Example 1: Basic Absolute Value
This example demonstrates the basic usage of the abs()
function with positive and negative integers and floating-point numbers:
# Working with negative integernegative_int = -15print(f"Absolute value of {negative_int} is: {abs(negative_int)}")# Working with positive integerpositive_int = 25print(f"Absolute value of {positive_int} is: {abs(positive_int)}")# Working with negative floatnegative_float = -12.7print(f"Absolute value of {negative_float} is: {abs(negative_float)}")# Working with positive floatpositive_float = 8.3print(f"Absolute value of {positive_float} is: {abs(positive_float)}")
The output of this code is:
Absolute value of -15 is: 15Absolute value of 25 is: 25Absolute value of -12.7 is: 12.7Absolute value of 8.3 is: 8.3
Example 2: Temperature Difference Calculator
This example shows a real-world scenario where abs()
is used to calculate the absolute difference between two temperatures, regardless of which temperature is higher:
def calculate_temperature_difference(temp1, temp2):"""Calculate the absolute difference between two temperatures"""# Use abs() to get positive difference regardless of orderdifference = abs(temp1 - temp2)return round(difference, 1)# Morning and evening temperaturesmorning_temp = 18.5 # Celsiusevening_temp = 12.3 # Celsius# Calculate difference using abs()temp_diff = calculate_temperature_difference(morning_temp, evening_temp)print(f"Morning temperature: {morning_temp}°C")print(f"Evening temperature: {evening_temp}°C")print(f"Temperature difference: {temp_diff}°C")# Works regardless of which temperature is highernight_temp = 8.1day_temp = 24.7temp_diff2 = calculate_temperature_difference(night_temp, day_temp)print(f"\nNight temperature: {night_temp}°C")print(f"Day temperature: {day_temp}°C")print(f"Temperature difference: {temp_diff2}°C")
The output generated by this code is:
Morning temperature: 18.5°CEvening temperature: 12.3°CTemperature difference: 6.2°CNight temperature: 8.1°CDay temperature: 24.7°CTemperature difference: 16.6°C
Codebyte Example: Distance Calculation with Complex Numbers
This example demonstrates using abs()
with complex numbers to calculate distances in a 2D coordinate system, useful in physics and engineering applications:
Frequently Asked Questions
1. Can abs()
work with complex numbers?
Yes, abs()
returns the magnitude (modulus) of complex numbers, which is the distance from the origin in the complex plane.
2. What happens if I pass a string to abs()
?
abs()
will raise a TypeError
because it only works with numeric types (int, float, complex).
3. What is the difference between abs()
and math.fabs()
?
abs()
works with integers, floats, and complex numbers, while math.fabs()
only works with floats and always returns a float.
4. Can abs()
be used with decimal numbers?
Yes, abs()
works with Python’s decimal.Decimal
objects as they implement the required numeric protocols.
5. What is the time complexity of abs()
?
abs()
has O(1)
time complexity for integers and floats, making it very efficient for mathematical operations.
All contributors
- MamtaWardhani
- design2461360801
- Henbeast
- christian.dinh
- Anonymous contributor
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours