To get absolute value in Python use abs
function. It is built-in function so no import is required.
For example:
abs(-11)
will return 11
, when:
abs(11)
will also return 11
.
Formally, absolute value is a value without a minus sing (-
) for all negatives and same value for all non-negatives. Note that 0
is non negative, so abs(0)
returns 0
.
Absolute value in python variable
You can call function passing variable also:
val = -2
val_abs = abs(val)
print(val_abs)
Will print 2
.
Float absolute value in python
You can also get an absolute for a float:
abs(-11.02)
Will return 11.02
.