# CS 1358 Introduction to Programming in Python SC7 ###### tags: `pythonSC` 1. If your program tries to print a variable that has not been defined, what kind of exception do you get? > NameError 2. What kind of exception do you get when you try z = 10 / 0? > ZeroDvisionError 3. What is the same between ZeroDivisionError and OverflowError? > ArithmeticError 4. What kind of exception do you get when you run? Why? ```python L = "hello world" print(L['5']) ``` > TypeError , string indices must be interger 5. Consider the following interactive session: ```console >>> int('25') 25 >>> int('0x25') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '0x25' ``` Even though 0x25 is a valid hex literal in Python, why do you still get ValueError? How do you correctly convert '0x25' into 37? Hint: type help(int) to get documentation on different ways of using the int() function. ```python int('0x25', base = 16) ``` 6. Which of the following expressions cause exceptions (and of what kind), assuming ```python L = "hello" L[4] L[0] L[5] <----------- L[-2] L[-5] L[-7] <----------- ``` 7. Suppose D = {'Sun': 0, 'Mon': 1, 'Tue': 2, 'Wed': 3}, which of the following expressions or assignment statements cause exceptions and of what kind? ```python D['Sun'] D[2] <----------- D['Thu'] <----------- D['Fri'] = 5 ``` 8. When you try to open a file by fh = open('filename', 'r') but cannot, what kind of exception do you get? > FileNotFoundError 9. When trying to open a file as in the previous question, how can your program check if an exception has occurred and inform the user by printing 'Cannot open file' to the standard output and continue running the rest of the program as usual? > use try exception 10. Suppose you are trying to execute the following sequence of statements. On which lines can exceptions occur and what types? How do you rewrite the code to check and handle all types of exception the same way by printing 'An error has occurred'? How do you rewrite the code to check each type of exception and print an error message for each specific exception? ```python= filenames = ['alpha', 'beta', 'gamma'] filenum = input('select a file by typing 1, 2, or 3:') i = int(filenum) fh = open(filenames[i], 'r') <----------- IndexError ``` 11. Given the following program ```python= try: x = int(input('enter num1:')) y = int(input('enter num2:')) z = x / y except ValueError: z = 0 except ZeroDivisionError: z = x print(z) ``` If an exception occurs on line 2, what lines of code are executed next? > line 6 If an exception occurs on line 3, what lines of code are executed next? > line 6 If an exception occurs on line 4, what lines of code are executed next? > line 8 If line 6 is execute, is it possible that lines 7-8 are also executed immediately after? > No If either line 6 or line 8 is executed, does line 9 also get executed next? > Yes 12. Given the following program ```python= greek = {'alpha': 0, 'beta': 1, 'gamma': 2} try: key = input('enter key alpha, beta, or gamma:') y = input('enter integer: ') z = greek[key] / int(y) except ValueError: print('invalid int') except ArithmeticError: print('arithmetic error') except ZeroDivisionError: print('zero division error') else: print('the value of z is', z) finally: print('last action before leaving try') ``` Which line or lines can cause one or more exceptions, of which types, and under what conditions? > line5 > KeyError: if user doesn't enter 'alpha', 'beta' or 'gamma'. > ValueError: if user doesn't enter an integer . > ZeroDivisionError: if user enters 0. In the case of zero division, is line 13 executed? Why or why not? If not, is ZeroDivisionError handled and by which line(s)? > no, line 9 will catch ArithmeticError If there is no exception by the end of line 5, which print statement or statements are executed next? > line 13&15 If the user does not input 'alpha', 'beta', or 'gamma' for the variable key on line 3, i. Which statements are executed next? > no statement execute next ii. Which statement causes an exception of which type? > KeyError iii. What statements are executed after the exception? > no statement execute next iv. Is the exception handled by any of the statements here? > no v. What happens to the exception after the entire code above is finished? > execute finally statement Suppose you want to modify the code above by handling both KeyError and ValueError exactly the same way by the same print('invalid input') statement, which lines do you modify into what code? ```python except (ValueError,KeyError): sys.stderr.write('invalid input') ``` 13. Failure to open a file causes an OSError, but how can you find out more information about the specific reason why the file cannot be opened? ```python except OSError as err: print(str(err)) ``` 14. Given the following code ``` python= import sys try: try: fh = open('myfile') A = int(fh.read()) B = int(fh.read()) quotient = A / B except (OverflowError, ZeroDivisionError): quotient = 0.0 else: quotient = 1.0 finally: print('exiting inner try') print('quotient = %f' % quotient) except OSError as err: sys.stderr.write(str(err)) ``` If an OSError occurs on line 4, do the following lines get executed? - [ ] line11 - [x] line13 - [x] line14 - [x] line16 15. Suppose you are writing a rock, paper, scissors game as follows: ```python= import sys rps = input('rock, paper, scissors, or quit? [rpsq]') if rps == 'q': sys.exit(0) elif rps in 'rps': play_game(rps) else: # report error in the form of a ValueError exception ``` Rewrite the code so that