How to Use abs Function in Python: Simple Guide
In Python, use the
abs() function to get the absolute value of a number, which means its distance from zero without the sign. It works with integers, floats, and even complex numbers by returning their magnitude.Syntax
The abs() function takes a single argument, which can be an integer, float, or complex number, and returns its absolute value.
- abs(x): Returns the absolute value of
x.
python
abs(x)Example
This example shows how abs() works with different types of numbers: negative integers, negative floats, and complex numbers.
python
print(abs(-10)) # Output: 10 print(abs(-3.5)) # Output: 3.5 print(abs(3 + 4j)) # Output: 5.0
Output
10
3.5
5.0
Common Pitfalls
One common mistake is trying to use abs() on non-numeric types like strings, which causes an error. Also, remember that abs() returns a float for complex numbers, not a complex number.
python
try: print(abs("-5")) # Wrong: string input except TypeError as e: print(f"Error: {e}") # Correct usage with integer conversion print(abs(int("-5")))
Output
Error: bad operand type for abs(): 'str'
5
Quick Reference
Here is a quick summary of how abs() behaves with different inputs:
| Input Type | Example | Output Description |
|---|---|---|
| Integer | -7 | Returns positive integer 7 |
| Float | -3.14 | Returns positive float 3.14 |
| Complex | 3+4j | Returns magnitude as float 5.0 |
Key Takeaways
Use
abs() to get the positive distance of a number from zero.abs() works with integers, floats, and complex numbers.Passing non-numeric types like strings to
abs() causes errors.For complex numbers,
abs() returns the magnitude as a float.