The abs() function in Python is used to return the absolute value of a number. It removes the negative sign from a number and returns its positive value.
Example: Find Absolute Value of a Number
num = -29
print(abs(num))
Output
29
Explanation: abs(-29) returns 29 by removing the negative sign.
Syntax
The abs() function has the following syntax:
abs(number)
- Parameter: number - Specifies an integer, floating-point number, or complex number.
- Return Value: Returns the positive value of the given number. For a complex number, it returns its magnitude.
Examples
Example 1: Find Absolute Value of an Integer
num = -94
res = abs(num)
print(res)
Output
94
Explanation:
- num contains the integer -94.
- abs(num) removes the negative sign.
- The result is 94.
Example 2: Find Absolute Value of a Floating-Point Number
float_number = -54.26
print('Absolute value of float is:',
abs(float_number))
Output:
Absolute value of float is: 54.26Explanation:
- float_number contains the floating-point value -54.26.
- abs(float_number) returns its positive value.
- The result is 54.26.
Example 3: Find Absolute Value of 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.0Explanation:
- complex_number contains the complex number 3 - 4j.
- abs(complex_number) calculates its magnitude.
- The magnitude is 5.0.
Example 4: Calculate Speed, Distance and Time Using abs()
Formula used:
- Distance = Speed * Time
- Time = Distance / Speed
- Speed = Distance / Time
The abs() function converts negative values into positive values before they are used in the calculations.
def cal_speed(dist, time):
return dist / time
def cal_dis(speed, time):
return speed * time
def cal_time(dist, speed):
return dist / speed
print("Speed:", cal_speed(abs(45.9), abs(-2)))
print("Distance:", cal_dis(abs(-62.9), abs(2.5)))
print("Time:", cal_time(abs(48.0), abs(4.5)))
Output
Speed: 22.95 Distance: 157.25 Time: 10.666666666666666
Explanation:
- abs(-2) converts -2 to 2.
- abs(-62.9) converts -62.9 to 62.9.
- The positive values are then used in the speed, distance, and time calculations.