Python abs() function is used to return the absolute value of a number.
It removes any negative sign in front of a number, making it positive.
Syntax
abs(n)
Parameters
n: It can be a integer, float or a complex number.
Return value
- For an integer or a float – returns the positive version of the number.
- For complex numbers – returns the magnitude of the complex number.
Example 1: Integer and floating-value
# Absolute value of a negative integer
print(abs(-5))
# Absolute value of a negative floating-point number
print(abs(-19.21))
# Absolute value of zero
print(abs(0))
Output
5
19.21
0
Example 2: Passing the complex number
print(abs(19 + 21j))
Output
28.319604517012593
Mathematically, the magnitude of a complex number a + bj is computed as:
Example 3: Time-Distance calculation
# Define the speed (in meters per second)
speed = 10
# Define the distance (in meters)
distance = -100
# Calculate the time it takes to travel the distance at the given speed
# Use the abs() function to ensure that the distance is positive
time = abs(distance) / speed
print(time)
Output
10.0
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
THANK YOU SO MUCH……….It helped me