Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
1: pi@raspberrypi ~ $ python3 py3prog/script1702.py
2:
3: Please enter number to divide: 3
4:
5: Please enter the divisor: 4
6:
7: The result is: 0.75
8: pi@raspberrypi ~ $
9: pi@raspberrypi ~ $ python3 py3prog/script1702.py
10:
11: Please enter number to divide: 3
12:
13: Please enter the divisor: four
14: Numbers entered must be digits.
15: Script terminating....
16:
17: pi@raspberrypi ~ $
18: pi@raspberrypi ~ $ python3 py3prog/script1702.py
19:
20: Please enter number to divide: 3
21:
22: Please enter the divisor: 0
23:
24: You cannot divide a number by zero.
25: Script terminating....
26:
27: pi@raspberrypi ~ $

In Listing 17.11, the script user makes an attempt with no problems on lines 1 through 7. Next, the
script user accidently enters the word four instead of the number 4 on line 13. The script captures
the raised exception and produces a user-friendly message instead of an ugly traceback. Also, notice
on lines 18 through 25 in Listing 17.11 that the ZeroDivisionError exception is still properly
handled.


Creating Multiple try except Statement Blocks


You can use multiple try except statement blocks throughout your Python scripts. In fact, it is
good form to put the blocks specifically around the Python statements that need them.


For example, looking back at the script script1702.py in Listing 17.10, you can see that the
ZeroDivisionError exception was potentially raised by the statement result = number
/ divisor. The ValueError exception could be raised by the input statements. Therefore,
good form dictates that those statements should be in their own try except statement blocks.


script1702.py has been revised and is now called script1703.py, as shown in Listing
17.12. This revised script properly divides the try except statement blocks for the Python
statements.


LISTING 17.12 Multiple try except Statement Blocks


Click here to view code image


1: pi@raspberrypi ~ $ cat py3prog/script1703.py
2: # script1703 - User Determined Division
3: # Written by Blum and Bresnahan
Free download pdf