Safe Digit Sum

Write two functions:

  • digit_sum(n), a recursive function that returns the sum of the digits of a non-negative integer n, raising ValueError("digit_sum requires a non-negative integer.") if n is not a non-negative integer.
  • safe_digit_sum(value), which calls digit_sum(value) inside a try/except, returning the result normally, or the string f"Could not calculate: {e}" (where e is the caught exception) if it fails.

Read an integer value and print the result of safe_digit_sum(value).

Example: 2024 → 2+0+2+4 = 8. -5 → an error message, not a crash.

main.py
Loading editor…

Console

Run your code to see output here.