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

(singke) #1
4: #
5: #####################################################
6: #
7: ################## Functions ########################
8: #
9: def divide_it ():
10: print ()
11: #
12: try:
13: # Get numbers to divide
14: number=int(input("Please enter number to divide: "))
15: print ()
16: divisor=int(input("Please enter the divisor: "))
17: print ()
18: #
19: except ValueError:
20: print ("Numbers entered must be digits.")
21: print ("Script terminating....")
22: print ()
23: exit ()
24: #
25: except KeyboardInterrupt:
26: print ()
27: print ("Script terminating....")
28: print ()
29: exit ()
30: #
31: try:
32: # Divide the numbers
33: result = number / divisor
34: print ("The result is:", result)
35: #
36: except ZeroDivisionError:
37: print ("You cannot divide a number by zero.")
38: print ("Script terminating....")
39: print ()
40: exit ()
41: #
42: #
43: ############## Mainline #############################
44: #
45: ...
46: pi@raspberrypi ~ $

Notice in Listing 17.12 that an additional exception has been added to the try except statement
block for the Python input statements in lines 25 through 29. This additional exception has been
added for catching keyboard interrupts, such as the user pressing Ctrl+C during data input.


Did You Know: Exception Groups
Exceptions belong to named exception groups. These exception group names can be
used in the except statement. For example, both ZeroDivisionError and
FloatingPointError exceptions belong to the ArithmeticError base
group. An except statement block could use ArithmeticError as its named
exception, like this:
except ArithmeticError:
Free download pdf