This assignment is Homework 16, and is due at classtime on Wednesday, April 5.

Assignment

  1. Consider the following Python code:

    def B(b_list): s = 0 for i in b_list: s += i return s def A(a_list): return B(a_list) print( A( [1, 2, 3] ) ) print( A( [1, "two", 3] ) )

    Function B() adds up a list of numbers, but if the list contains a non-numerical entry, the function will raise a TypeError. Modify function A() so that the call to function B() is inside of a try block and any TypeError is handled by printing a helpful message for the user.

  2. Write a program that asks the user for the name of a file. The program should then attempt to open the file and print the contents of the file. However, if the program is unable to open the file, it should handle the resulting exception and print a helpful error message.

  3. Modify your previous program so that, if the program cannot open the file, it gives the user two choices: either enter another file name and try again, or quit. The program should continue trying to open files, either until it successfully opens a file or the user chooses to quit.

  4. We previously used the following code to retrieve a file from a web server:

    import urllib.request F = urllib.request.urlopen( someURL )

    However, the function urllib.request.urlopen() can raise various exceptions. For example, it raises a ValueError if it cannot interpret its argument as a valid URL. It also raises a urllib.error.HTTPError if the server cannot find the requested file. To see this for yourself, run the following code:

    import urllib.request urllib.request.urlopen( "test" ) #this line raises a ValueError urllib.request.urlopen( "http://www.mlwright.org/nofile.txt" ) #this line raises a urllib.error.HTTPError

    Write a program that asks the user for a URL and then uses urllib.request.urlopen() to request that URL. If urllib.request.urlopen() raises a ValueError or urllib.error.HTTPError, then your program should handle the exception and print a helpful message for the user.

Submitting your work

After you have finished your solutions, paste them into a single Python file. Make sure that Python can run your file without error! Please use comments (lines that begin with a # symbol) to clearly state the problem number for each solution in your file. Save your file and upload it to the HW16 assignment on Moodle.