Absolute value of a number in Python

We can get the absolute value of a number in Python using fabs() function. The function is provided by math module. In addition to, abs() function can also be used. But, before that a bit about absolute value of a number itself.

Absolute value of number ‘x’ would be –

x if x>0 and,

x if x<0

This implies, if value of x is greater than zero then, absolute value of x is x itself. But, if value of x is less than zero i.e. negative real number then, absolute value of -x would be x. Also, this applies only for real numbers. Things get different in case of complex numbers.

Absolute value of a number using fabs() in Python

We would first get the numerical input from the user. Thereafter, fabs() function provided by math module is used to get the desired outcome.

#Ask the user to input a number
x=float(input("Enter a number: "))

import math
absolute=math.fabs(x)
print("The absolute value of ",x," is", absolute)

Here, we are using float data type to get the input from the user. This is for floating point numbers i.e. to include those containing decimal fractions. The input is stored in variable ‘x‘.

Then, math module is imported. math.fabs(x) gets us the absolute value of input stored in variable ‘x‘ and the result is stored in variable ‘absolute‘.

Lastly, we can get the desired outcome using print() function.

Absolute value of a number using abs() in Python

Alternately, we can also get the absolute value of a number using abs() function.

#Ask the user to input a number
x=float(input("Enter a number: "))

print("The absolute value of ",x," is", abs(x))

Variable ‘x‘ stores the input from the user. Then, we get the desired outcome by using abs() function inside the print() function directly.

In conclusion, we have discussed how to get the absolute value of a number in Python using fabs() and abs() functions.

Additional Info –

In this article, we have discussed how to get the absolute value of real numbers. We can also get the absolute value of complex number too. Complex numbers are expressed as x+yi, where x and y are real numbers. We will be discussing that in coming articles.