Outline for May 22, 2014

Reading: text, §12, A
Due: Homework #4, due May 30, 2014

  1. Examples
    1. Put lines in a file in random order [randlines.py]
    2. Read in a list of words from a file, then search it as requested; similar to linear search program [search-1.py]
    3. Now see how many words you checked total [search-1c.py]
  2. Gotchas!
    1. What to do when a function returns a value
    2. if x == ’a’ or ’A’
    3. Scope, especially defining functions within functions
  3. Namespaces
  4. Importing modules
    1. import math
    2. from math import sin, cos, sqrt
    3. from math import *
  5. time module
    1. time.clock()
    2. How to time a function call
  6. Debugging
    1. Syntax errors: where Python notices it, not necessarily where it is
    2. It (seems to do) nothing: usually forgot to call something
    3. It hangs: look for an infinite loop or a recursion with no base case (or one that may not be reached) — print is your friend!
    4. Tracing flow of execution: put print statements at beginning, end of each function saying which function you are entering and leaving; printing parameters, return values can be very useful
    5. Exceptions
      1. NameError: variable doesn’t exist in local environment
      2. TypeError: using a value improperly (like indexing a string with a non-integer); item in format string doesn’t match item, or conversion is invalid; passing wrong number of arguments to a function or method
      3. IndexError: index of string or list element is out of bounds
      4. AttributeError: referencing a method that doesn’t exist
    6. Semantic errors: try to figure out where the error occurs (hand-running a simple case, or using pythontutor.org, is very helpful)
    7. Simplify — complex expressions sometimes need to be written as two or more statements
    8. Still can’t get the bug: take a walk outside, get away from the program for a bit, ask a friend to look at the program

You can also obtain a PDF version of this. Version of May 21, 2014 at 10:54PM