09 Prepare : Checkpoint B - More exceptions
After completing (or while completing) the preparation material for this week, complete the following exercise.
Overview
This checkpoint is intended to help you practice the syntax of exceptions.
Instructions
Write a program that computes the value of 1/n for different values of n. To accomplish this, adhere to the following guidelines:
Make a function
get_inversethat accepts a number, n, and then returns the result 1/n.In main, prompt the user for the value, then pass it to your
get_inverse, and save the result in a variable. Finally, display the result.Create a new exception type:
NegativeNumberErrorthat inherits fromExceptionIn the
get_inversefunction you should check for the following rules and raise an appropriate exception. Do not display any error messages in this function, simply raise the exception.n is not a number: ValueError
n is 0: ZeroDivisionError
n is less than 0: NegativeNumberError
In main, catch each exception and display the following error messages:
ValueError: "Error: The value must be a number"
ZeroDivisionError: "Error: Cannot divide by zero"
NegativeNumberError: "Error: The value cannot be negative"
If an exception occurred, do not display the result. If no exception occurred, then display the result as normal.
Sample Output
The following is an example of output for this program:
Enter a number: 4
The result is: 0.25
Here is another example:
Enter a number: word
Error: The value must be a number
Here is another example:
Enter a number: 0
Error: Cannot divide by zero
Here is another example:
Enter a number: -10
Error: The value cannot be negative
Testbed
An auto-grading testbed script is provided for you to help evaluate your program. This same testbed script will be used to grade your program. It is pass/fail, so your program must pass the testbed completely for you to receive credit for this assignment. You may run the testbed as many times as you like.
You must use exceptions for this program in order to receive credit. Similarly, you must raise the errors in one function and catch them in another.
Helpful commands
testBed cs241/check09b check09b.py
submit check09b.py