abs() Absolute value of number

abs function returns absolute value of input number ( with same dtype ).
abs() is a built-in function of Python so no need to import any module.

Here are some examples with different type of numbers.
print(abs(-4))    # 4
print(abs(-4.6))  # 4.6
print(abs(4))     # 4
print(abs(4.6))   # 4.6
Data type of the output is same as input number.
print(type(abs(-4)))    # <class 'int'>
print(type(abs(-4.6)))  # <class 'float'>
print(type(abs(4)))     # <class 'int'>
print(type(abs(4.6)))   # <class 'float'>

Example 1: Using abs() with Negative Floats

negative_float = -7.25
print(abs(negative_float))  # Output: 7.25

Example 2: Applying abs() to Complex Numbers

complex_num = 3 + 4j
print(abs(complex_num))  # Output: 5.0

Example 3: Using abs() in a List Comprehension

We can apply abs() to every value using list comprehension.
numbers = [-1, 2, -3, 4, -5]
absolute_numbers = [abs(num) for num in numbers]
print(absolute_numbers)  # Output: [1, 2, 3, 4, 5]

Example 4: Calculating Distance Between Two Points

point1 = (3, 4)
point2 = (7, 1)
distance = abs(point2[0] - point1[0]) + abs(point2[1] - point1[1])
print(distance)  # Output: 7

Example 5: Handling User Input with abs()

user_input = input('Enter a number: ')
number = float(user_input)
print('The absolute value is: ', abs(number))

Difference between fabs() and abs()

fabs() is included in Python math module so we have to import it before using. Where as abs() is part of built in functions of core Python so no need to import any library.

fabs() returns always float dtype. Whenever input number can't be converted to float , fabs() generates error. However abs() returns the same dtype of input number.

Variables in Python Keywords in Python
All Built in Functions in Python


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer