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

(singke) #1

exception. This is done in script1701.py.


LISTING 17.7 A try except Statement Block


Click here to view code image


1: pi@raspberrypi ~ $ cat py3prog/script1701.py
2: # script1701 - Properly handle Divide by Zero Exception
3: # Written by Blum and Bresnahan
4: #
5: #####################################################
6: #
7: ################## Functions ########################
8: #
9: def divide_it ():
10: print ()
11: number=int(input("Please enter number to divide: "))
12: print ()
13: divisor=int(input("Please enter the divisor: "))
14: print ()
15: try:
16: result = number / divisor
17: print ("The result is:", result)
18: #
19: except ZeroDivisionError:
20: print ("You cannot divide a number by zero.")
21: print ("Script terminating....")
22: print ()
23:#
24:############## Mainline #############################
25:#
26:def main ():
27: divide_it ()
28:#
29:############ Call the Main Function ###################
30:#
31:main()
32: pi@raspberrypi ~ $

Notice that the script in Listing 17.7 has input statements on lines 11 and 13. The script asks the
script user for the number to be divided and its divisor. Because a script user could enter the number
0 here for the divisor, the math statement using the input is included in the try statement block.


The idea is to allow the script to continue working as normal as long as no exceptions are raised. If
an exception is raised, Python statements in the except statement block handle it. In Listing 17.8, on
lines 1 through 7, the script runs fine. The script user has input appropriate data, and thus no
exceptions are raised.


LISTING 17.8 Execution of Script script1701.py


Click here to view code image


1: pi@raspberrypi ~ $ python3 py3prog/script1701.py
2:
3: Please enter number to divide: 3
Free download pdf