Skip to main content.

Lab 9: Modules, Exception Handling, and Dictionaries

Goals

After the lab, you should be proficient at

  1. creating our own modules
  2. handling exceptions
  3. using dictionaries to solve problems

Objective: Review

Review the slides for today's lab.

Objective: Set Up

Objective: Programming in Python

Your programs will be graded on correctness, style, efficiency, and how well you tested them. Make sure you adhere to the good development and testing practices we discussed in class. Your code should be readable and your output should be useful and well-formatted.

  1. (20) Creating a module. Modules are a way that we can make our code easier to reuse and share. We've used modules but haven't made our own modules. That changes now.

    Copy lab8.2.py into your lab9 directory and name it caesarcipher.py. Create a new file called lab9.1.py. Move the main function and calling the main function from caesarcipher.py into lab9.1.py. Confirm: caesarcipher.py should contain only the definitions of the encoding functions and the test functions and maybe constants.

    Near the top of lab9.1.py, import your module by adding an import statement: from caesarcipher import *

    Run lab9.1.py to confirm that it still works as expected.

    Next, modify caesarcipher.py to call your test functions at the bottom of the file. Run lab9.1.py. What happened?

    To handle that issue, we need to add some code into caesarcipher.py: put the calls to the test functions into the body of an if statement, specifically: if __name__ == "__main__":

    Run caesarcipher.py. What happens?

    Run lab9.1.py. What happened?

    Reflection: Explain in comments in caesarcipher.py what the effect of adding that if statement was, on both caesarcipher.py and lab9.1.py.

    For your .out file, demonstrate that lab9.1.py works correctly.

  2. (10) Copy lab8.1.py as lab9.2.py. Modify it to use the caesarcipher.py module and remove the now-unnecessary code.

    Reflection: In comments, explain how using the module affected this code (as compared to lab8.1.py).

    For your .out file, demonstrate that the program works correctly.

  3. (20) Copy lab9.1.py as lab9.3.py. Modify caesarcipher.py to do exception handling when reading the file, and lab9.3.py to do exception handling when writing to the file. When a problem with reading or writing a file occurs, display a descriptive error message and then exit the program. To exit the program, you'll need to import sys at the top of the program and then call sys.exit(). Update the doc string for the function that reads the file accordingly.

    Demonstrate that the program works as expected on files that exist and displays an error message on files that don't. For writing files, try writing to a location that you don't have permission to write to, e.g., /etc/myfile.txt

    Note that we can't set up our test functions to be able to check that the exception behavior works with the way we have our functions set up.

  4. (10) Using a dictionary object, create a program that maps a letter to an example word that starts with that letter. You must have at least three entries in your dictionary. Then, print out the dictionary so that it looks similar to a children's book, and the keys are printed in alphabetical order. Example output looks like:
    f is for fiddle
    g is for goose
    z is for zoo
    
  5. (30) The most common last names for people in the United States are Smith, Johnson, and Williams. The most common first names for females are Mary, Patricia, and Linda and for males are James, John, and Robert. (Source: Name Statistics) In this program, you are going to determine the most common names for W & L students.

    Your program will read in a text file of names (one name per line), count how many times each name occurs in the text file, and print out the names (in alphabetical order) and the number of times each name occurs. (Note that this problem is slightly simpler than what we did in class because we know that the only thing on a line in the file is the name.)

    There are five data files in the data directory for you to process. File test.txt is provided as an easier first file to test. The remaining four files represent W&L undergraduate's last names, first names, female first names, and male first names.

    Implement your code on one file. (The lastnames.txt file will be the easiest "real file" to check that your work is correct because the file is in alphabetical order.)

    You can add the following code to your code to enable some "spot checks" for correctness. Note: the code may need to be modified slightly, depending on how you named variables.

          while True:
              name = input("What name do you want to check? ")
              if name in nameToCount:
                  print(name, "occurs", nameToCount[name], "times.")
              else:
                  print(name, "was not in the data.")
        

    Hit Control-C to exit the while loop.

    Next, to make later development a little simpler, refactor your code so that you have a function that takes the name of the file (a string) as a parameter. The function should process the file and return the generated dictionary. The main function should then display the (alphabetized) contents of the returned dictionary.

    Finally, modify your main to call the function four times, once for each of the data files.

    Don't save the output from this program--it's too much to print! Just look at the output yourself and verify that it makes sense.

    While this is useful output, we can't easily determine the name that occurs most frequently, and we can't see trends in names' frequencies. We will work on that soon.

  6. Finishing up: What to turn in for this lab

    1. IDLE and jEdit may create backup files with the "~" extension. Delete these files from your lab directory to save paper when you print.
    2. Submit your lab9 directory into your turnin directory.
    3. Remove any .pyc files from the directory; otherwise, you'll get an error when creating the output file.
    4. We actually didn't use two of the files I gave you (e.g., generateFreqGraphs.py and graphing_example.py) because we have to wait until next week for that.
    5. Perform the following steps from your cs111 directory.

      Note that each command below links to a page with more information about using the command.

    6. Create the printable lab assignment, using the createPrintableLab command:
      createPrintableLab <labdirname>
    7. View your file using the evince & command.
    8. Print the file using the lpr command.
    9. Log out of your machine when you are done.

    Labs are due at the beginning of Friday's class. You should hand in the printed copy at the beginning of class, and the electronic version should be in the turnin directory before class on Friday.

    Ask well before the deadline if you need help turning in your assignment!

    Grading (90 pts)