For an ordinary Python int or float, you can get the absolute value without calling abs() by using a conditional expression: x if x >= 0 else -x. It returns x when x is nonnegative and its negation otherwise. The pattern is sound for ordered real numbers. Complex numbers and NaN need different handling, which is covered below.
The manual implementation
The one-line form is the most compact option:
x = -7
absolute_value = x if x >= 0 else -x
print(absolute_value) # 7
The same logic written as a full statement is easier to read in teaching code or when the branch needs more work:
if x < 0:
absolute_value = -x
else:
absolute_value = x
Why the pattern works
The condition picks one of two operands. A nonnegative value is kept as it is. A negative value goes through unary negation, which flips its sign and leaves a positive result. Because the operand is returned unchanged, the result keeps the input’s type: an int stays an int and a float stays a float.
Unary negation on its own is not absolute value. Multiplying by -1 or applying -x to every input would flip positive numbers too, so the test on the sign is what makes the technique work.
#1 Best Overall
One edge case is worth knowing. Negative zero (-0.0) satisfies -0.0 >= 0, so the conditional returns -0.0. The built-in abs(-0.0) returns 0.0. In arithmetic the two behave the same, but they print differently and can matter in formatting or sign-sensitive code.
Alternatives that avoid calling abs() by name
math.fabs() for floating-point code
math.fabs(x) from the math module returns the absolute value as a float, even when you pass an integer. The function is for real numbers and rejects complex input.
Rank #2
import math
math.fabs(-7) # 7.0
math.fabs(-2.5) # 2.5
Use it when a float result is acceptable and a function call is not forbidden. If your code must preserve int type, the conditional expression is the better fit.
Decimal values
The decimal module provides its own absolute-value operation. For a Decimal instance, copy_abs() returns the absolute value, and the decimal context also offers an abs operation. Decimal supports special values such as NaN and infinities, and those follow the Decimal module’s own rules, so check them against your policy before relying on a branch.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minutefrom decimal import Decimal
Decimal("-2.50").copy_abs() # Decimal('2.50')
If your restriction covers only the built-in abs() call, the method is a legitimate alternative. If the restriction covers any absolute-value operation, a manual conditional on the Decimal value still works for ordinary finite numbers.
Complex numbers
Complex values cannot be used with < or >=. Python does not define an ordering for complex numbers, so the conditional pattern raises a TypeError instead of returning a magnitude. Comparing a complex number with zero is not a workaround either.
The mathematically meaningful quantity is the magnitude, the distance from the origin in the complex plane. You can compute it directly from the real and imaginary parts:
import math
z = 3 + 4j
magnitude = math.hypot(z.real, z.imag) # 5.0
This is the same quantity the built-in abs() returns for complex input, so use it only if the exercise or policy allows explicit magnitude computation.
Best Value
Where the conditional approach fails
NaN values
NaN is not an ordinary ordered value. Every ordered comparison with NaN returns false, so x >= 0 is false and -x returns NaN as well. The branch therefore gives no meaningful answer for NaN without an explicit rule. The simplest documented policy is to return NaN unchanged, and the check for it uses the fact that NaN is the only value not equal to itself:
def manual_abs(x):
if x != x: # NaN check
return x # policy: propagate NaN
return x if x >= 0 else -x
If your code should reject NaN instead, raise a ValueError in the same branch.
Types without an ordering
The conditional works only when the input supports >= with zero and negation. That covers int, float and Fraction. It fails for complex numbers, as described above, and for any custom numeric type that does not define these operations.
Choosing an approach
| Input type | Expression | Result type | Limitation |
|---|---|---|---|
Real int or float, no function call needed |
x if x >= 0 else -x |
Same as input | Returns -0.0 for negative zero; NaN needs a separate check |
| Real number, float result acceptable | math.fabs(x) |
float | Rejects complex input; always returns float |
Decimal |
x.copy_abs() |
Decimal |
Special values (NaN, infinities) follow Decimal rules |
| Complex number | math.hypot(z.real, z.imag) |
float | Requires explicit computation; no ordering exists for the conditional |
| Float that may be NaN | NaN check plus conditional | Same as input for numbers | The policy for NaN (propagate or raise) must be chosen and documented |
Common mistakes
- Using
x * -1for every input. It turns positive values negative. - Treating
-xas absolute value. Negation only reverses the sign. - Assuming
x < 0works for all Python numbers. It fails for complex values and gives false results for NaN. - Expecting
math.fabs()to keep integers as integers. It always returns a float. - Calling a value “positive” when you mean its absolute value. These differ for special values and for types with no ordering, so the conditional is only a correct absolute value where the ordering applies.
Which approach to use
- Exercise that forbids
abs()with plain numbers: use the conditional expression and state that it covers real numbers. - Floating-point code where a call is acceptable: use
math.fabs(). - Decimal money or precision work: use
copy_abs()if only the built-in call is restricted. - Complex input: compute the magnitude explicitly with
math.hypot(), and say so in the code’s documentation. - Production code with no restriction: the built-in
abs()is the idiomatic choice. It handles integers, floats, Decimal and complex numbers without extra branching.
The conditional expression is a teaching and restricted-environment tool. It is not a replacement for abs() in general code.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Sources and version notes
The behavior described here is documented in Python’s reference pages for the built-in functions, the expression reference (which covers comparisons and NaN), the math module and the decimal module. The conditional expression relies only on core syntax. The math.fabs() and Decimal methods have been part of the standard library for many years, but if you target an older interpreter, confirm each call against your project’s Python version.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




