Validate a Positive Integer Input

Easy ⏱ 8 min 76% acceptance ★★★★★ 4.8
Write a function safe_sqrt(n) that returns the square root of n (as a float) if n is a non-negative number, and returns the string "Invalid input" if n is negative. Validate before computing.

Examples

Example 1
Input
safe_sqrt(16)
Output
4.0
Explanation

16 is non-negative, so its square root 4.0 is returned.

Example 2
Input
safe_sqrt(-4)
Output
Invalid input
Explanation

Negative input is rejected before any computation is attempted.

Constraints

  • n may be an int or a float.
  • Do not let math.sqrt raise an exception for negative input — validate first.

Topics

Functionsinput validation

Companies

SalesforceServiceNow

Hints

Hint 1

Check `if n < 0` before calling sqrt.

Hint 2

n ** 0.5 also computes a square root without importing math.

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