Page 219 - Beginning Programming with Pyth - John Paul Mueller
P. 219

1. Type the following code into the notebook — pressing Enter after
each line:
               try:
                  Value1 = int(input("Type the first number: "))
                  Value2 = int(input("Type the second number: "))
                  Output = Value1 / Value2
               except ValueError:
                  print("You must type a whole number!")
               except KeyboardInterrupt:
                  print("You pressed Ctrl+C!")
except ArithmeticError:
print("An undefined math error occurred.")
               except ZeroDivisionError:
                  print("Attempted to divide by zero!")
               else:
                  print(Output)
The code begins by obtaining two inputs: Value1 and Value2. The first two except clauses handle unexpected input. The second two except clauses handle math exceptions, such as dividing by zero. If everything goes well with the application, the else clause executes, which prints the result of the operation.
2. Click Run Cell.
Python asks you to type the first number.
3. Type Hello and press Enter.
As expected, Python displays the ValueError exception message.
However, it always pays to check for potential problems.
4. Click Run Cell again.
Python asks you to type the first number.
5. Type 8 and press Enter.
The application asks you to enter the second number.
6. Type 0 and press Enter.
You see the error message for the ArithmeticError exception, as shown in Figure 10-7. What you should actually see is the ZeroDivisionError exception because it’s more specific than the ArithmeticError exception.
7. Reversetheorderofthetwoexceptionssothattheylooklikethis:p except ZeroDivisionError:
                  print("Attempted to divide by zero!")
               except ArithmeticError:
print("An undefined math error occurred.")
8. Perform Steps 4 through 6 again.
 

































































   217   218   219   220   221