Skip to main content

Section 12.2 try and except

To catch errors in your program, you use the keyword try, followed by a block of code that might have an error. The try clause is followed by the except keyword and a block that tells what to do when an exception occurs.
Here is an example of asking a user for numeric and catching a ValueError in case they do not enter a number. Try this code and enter 27 (a number) and five (not numeric) to see what happens:

Checkpoint 12.2.1.

You can now write a function called get_float which takes a prompt string as its parameter and returns a user’s input. The function will continue to ask the user for input as long as the input is non-numeric.
Here is what output from a sample run might look like. Your output does not have to match this exactly, but it must convey the same information.
Enter price:five dollars and 78 cents
Please use numeric input.
Enter price:5.78
Enter discount percent:2
Price after discount is $5.66.