Ternary Rewrite: Absolute Value

Easy ⏱ 8 min 85% acceptance ★★★★★ 4.7
Write a function abs_value(n) that returns the absolute value of n using a single conditional (ternary) expression — no if statement blocks and no built-in abs().

Examples

Example 1
Input
abs_value(-8)
Output
8
Explanation

Negating -8 gives 8.

Example 2
Input
abs_value(3)
Output
3
Explanation

3 is already non-negative.

Constraints

  • n is an integer or float.
  • Must be implemented as one conditional expression, e.g. `x if cond else y`.

Topics

Conditional Statementsternary operator

Companies

AdobeSalesforce

Hints

Hint 1

Python's ternary form is `value_if_true if condition else value_if_false`.

Hint 2

Return `n` when `n >= 0`, otherwise return `-n`.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.