Python abs()
Function
The abs() function in Python returns the absolute value of a number.
Syntax
abs(number)
Parameters:
number
– An integer, float, or a number that implements__abs__()
Returns:
- The non-negative absolute value of the given number.
Example: Using abs()
with Integers
print(abs(-5))
5
Example: Using abs()
with Floats
print(abs(-3.14))
3.14
Use Case: Why is abs()
Useful?
- Helps in finding the distance between numbers
- Commonly used in sorting, graphs, and measurements
- Useful in mathematical functions like distance calculations
Handling Complex Numbers
print(abs(3 + 4j))
5.0
This is because abs()
returns the magnitude of a complex number.
Common Mistakes
- Passing a string will raise a
TypeError
- Only numerical types are supported unless a class implements
__abs__()
Interview Tip
In coding interviews, abs()
is often used in problems involving distances, differences, or comparisons.
Summary
abs()
returns the absolute value- Supports
int
,float
, andcomplex
- Raises
TypeError
if the argument is not numeric
Practice Problem
Write a program that reads a number from the user and prints its absolute value.
num = float(input("Enter a number: "))
print("Absolute value is:", abs(num))