-3

How can I write a function sqrt(f:float) -> float that returns the square root of f when f is non-negative. However, if f is negative, your function should raise a ValueError exception stating that the input value f cannot be negative.

For example:

sqrt(4.0)
2.0
sqrt(-1)
Traceback (most recent call last):
...
ValueError: input value cannot be negative

Here is my code, which doesn't really work... what changes should I make?

import math
def sqrt(x):
    try:
        if x > 0:
            return math.sqrt(x)
        else:
            return ("ValueError")
    except ValueError:
        return ("ValueError: input value cannot be negative")

2 Answers2

0

You don't "return" an error; you raise the ValueError exception.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Use raise keyword.

import math
def sqrt(x):
    if x < 0:
        raise ValueError("input value cannot be negative")
    return math.sqrt(x)
Ratery
  • 2,863
  • 1
  • 5
  • 26