Three ways to find the absolute value of python
- Conditional judgment
- Built-in function
abs()
- Built-in module
math.fabs
import math
# Method 1, Keywords: Conditional judgment
def abs_value1():
a = int(input('please enter a number:'))
if a > 0:
print(a)
else:
print(-a)
# Method 2, Keywords: Built-in function
def abs_value2():
a = int(input('please input-number:'))
b = abs(a)
print(b)
# Method 3, Keywords: Built-in module
def abs_value3():
a = int(input('Please enter a number:'))
b = math.fabs(a)
print(b)
The difference between abs() and fabs()
abs()
is a built-in function, and fabs()
is defined in the math module.
- The
fabs()
function is only suitable for float and integer types, and abs()
is also suitable for complex numbers.
abs()
returns float and int types, math.fabs()
returns float types