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'>
negative_float = -7.25
print(abs(negative_float)) # Output: 7.25
complex_num = 3 + 4j
print(abs(complex_num)) # Output: 5.0
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]
point1 = (3, 4)
point2 = (7, 1)
distance = abs(point2[0] - point1[0]) + abs(point2[1] - point1[1])
print(distance) # Output: 7
user_input = input('Enter a number: ')
number = float(user_input)
print('The absolute value is: ', abs(number))
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.