Reading: text, §12, A Due: Homework #4, due May 30, 2014
Examples
Put lines in a file in random order [randlines.py]
Read in a list of words from a file, then search it as requested; similar to linear search program [search-1.py]
Now see how many words you checked total [search-1c.py]
Gotchas!
What to do when a function returns a value
if x == ’a’ or ’A’
Scope, especially defining functions within functions
Namespaces
Importing modules
import math
from math import sin, cos, sqrt
from math import *
time module
time.clock()
How to time a function call
Debugging
Syntax errors: where Python notices it, not necessarily where it is
It (seems to do) nothing: usually forgot to call something
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!
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
Exceptions
NameError: variable doesn’t exist in local environment
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
IndexError: index of string or list element is out of bounds
AttributeError: referencing a method that doesn’t exist
Semantic errors: try to figure out where the error occurs (hand-running a simple case, or using pythontutor.org, is very helpful)
Simplify — complex expressions sometimes need to be written as two or more statements
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