Error and Exception Handling · 14 / 20 Exercise Medium

Validated square root

Objective

Create a Python program with a function that calculates the square root and raises an exception when the number is negative.

Instructions

  • Define the function square_root(x): if x is negative, raise ValueError("Negative number") with raise; otherwise, return math.sqrt(x).
  • Read a decimal number and call the function inside a try block.
  • If all goes well, show the root with two decimals.
  • If the exception is raised, show Error: followed by the exception message.
Input
16
Output
4.00

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise