[ answers in web view ]
Name: _______________________________ K E Y
Student ID: _______________________________

Total points: 70
  1. Fill in the blank: [6]
    1. In software development, the document that describes the functionality you intend to deliver to the client is called the specifications________________.
    2. When we wish to print() an object to the console, which method of the object does Python invoke? __str__()_______________.
    3. In a Python class, the __init__() method is the special method called the constructor or initializer____________________.
    4. The Python method on file objects that sets the file pointer (location within the file) is called seek()__________
    5. What English part of speech should a method name be? verb___________
    6. Let myList = [ 9, 8, 7, 6 ]. What is myList[1:3]? [8, 7]_____________
  2. What are exceptions used for? What happens when one is raised? [4]
    Exceptions are used to signal an error or out-of-the-ordinary situation. When one is raised, normal execution of the program terminates, and control jumps to the nearest enclosing exception handler that can catch that exception. The exception handler typically would clean up and notify the user of the error, before either exiting gracefully or continuing on.
  3. Compare and contrast Python lists with C/M2 arrays [4]
    Python lists can change length (can insert/delete), can have items of differing type, can have items which change type (due to Python's dynamic typing), and have various operators/functions defined on them, such as del, len(), negative indexing, list slicing, etc.
  4. What is output by the following block of Python code? [3]
    myList = [ "Hey bub!", ("hey", "bub!"), range(10, 40, 5), [ range(5) * 2 ] ]
    for item in myList:
    	print( len(item), end=' ' )		# print all on one line
    

    '8 2 6 1 '
  5. What is serialization, and why is it useful? What does it look like in Python? (Just describe the library and primary functions; no need for complete code.) [5]
    Python's pickle library is an implementation of serialization, which converts Python objects to string representations and back. These string representations can be stored in files, transferred to other programs, or sent over a network. I/O of complex data structures is facilitated by serialization. An object that has been pickled can be unpickled and retain all its original structure, types, and values.
  6. Describe all the various file modes in which Python can open a file, as though you were writing a manual for the function open(). Indicate any errors that might occur and anything that a Python programmer using open() might need to watch out for. [5]
    'r': read-only (assumes file exists and is readable)
    'w': write-only (assumes file can be created/written; if file already exists, its old contents are clobbered)
    'a': append (assumes file is writable; if file already exists, it is appended to)
    'r+': read+write (overwrites bytes in-place)
    'rb', 'wb', etc.: binary modes, for reading/writing binary data instead of text data
  7. What is a stub function, and why might such things be useful in software development? Describe an example.[5]
    In top-down design of a complex software system, it is helpful to build the general framework first, and fill in the details later. An analogy is building the frame of a house first, then filling in the wiring, plumbing, drywall, and appliances later. A stub function is a placeholder for a complete function; it does not perform the computations yet but always returns a dummy value, e.g., 0. An example is our ROT13 program, when we had the framework of converting between letters and ASCII codes, but did not actually do the ROT13 encryption arithmetic.
  8. Recall that in Python int/float/bool parameters are essentially passed by value, and lists/object parameters are essentially passed by reference. What is printed by the following block of Python code? [4]
    	def double_me(x):
    		x *= 2
    	y = 3
    	z = list(range(3))
    	double_me(y)
    	double_me(z)
    	print( 'y =', y, ', z =', z )
    
    y = 3, z = [0, 1, 2, 0, 1, 2]
    
    The variable y points to an immutable object (the float 3.0) and is roughly pass-by-value, so it is not affected by double_me(). The variable z points to a mutable object (the list range(3)) and is roughly pass-by-reference, so it is changed by double_me(). The real scoop on Python parameter passing is call-by-object and is a bit more complicated; it has to do with Python's object-oriented roots.
  9. Define or describe each of the following terms in object-oriented programming: [5]
    1. Class: a user-defined container type
    2. Instance: an object; instances are to classes as variables are to types
    3. Attribute: a variable or method belonging to an object
    4. Method: a function/procedure belonging to an object
    5. Constructor/initializer: the special method which is called when an object is instantiated
  10. What are set/get (mutator/accessor) methods, and why are they a good idea? Describe an example.[5]
    Allow controlled access to private attributes. An objects' attributes should be made private (in Python, name starts with '__') so that code outside the class definition cannot directly access the attributes and must use the provided set/get methods. Benefits include error checking / input validation, user permissions, transaction logging, etc. For instance, the Fraction example had a denominator attribute; it would be bad if external code could directly set the denominator to zero, so the Fraction class provides a setDenom() method which ensures that the new denominator is not zero.
  11. Design a class Song that represents a single song (e.g., MP3) in your music collection (e.g., iTunes). What attributes are needed (and what types are they)? What methods are desirable? No Python code is needed, just discussion. [6]
    Many possible answers; the point is to discuss possible attributes (data stored with each song) and methods (actions to perform involving a song).
    Attributes: Title, Artist, Album (all strings), Year (int), audio stream (either directly as a big object, or as a string referring to a filename on disk)
    Methods: set/get methods, play(), etc.
  12. Write a Python function clicker(x,y,s) (taking 3 parameters) which uses Zelle's graphics.py library to draw a window with a button in it, and waits for the user to click. The button should be centred around the coordinates (x,y) and have a text string label given by the parameter s. When the user clicks, the function should return a boolean value indicating whether the user clicked the button or not. [8]

    Docstring, pseudocode, comments, etc. are not required, but may be helpful for partial credit if your code isn't right. You may assume graphics has been imported, but do not assume a window has been made already. It's okay if you don't remember the exact names of the classes/functions in the graphics.py library; just use pseudocode or make a guess as to the name. Don't worry about whether the label will fit within the button; just choose some reasonable dimensions for the window and the button.
    def clicker(x,y,s):
    	from graphics import *
    	win = GraphWin("Clicker!", 400, 300)
    	left, right, top, bottom = x-100, x+100, y-20, y+20
    	Rectangle(Point(left,top), Point(right, bottom)).draw(win)
    	Text(Point(x,y), s).draw(win)
    	click = win.getMouse()		# wait for user
    	return (left <= click.x <= right) and \
    		(top <= click.y <= bottom)
    
  13. Write a Python program to read in integers from the file "input.txt", one per line, square each number (i.e., multiply it by itself), and print the results (one per line) to the file "output.txt". For example, "input.txt" might look like the following:
    13
    -5
    0
    100
    Lines in the input file which do not conform to this format should be skipped (don't assume that the input file will be formatted properly!). Your program would output something like this:
    169
    25
    0
    10000
    You should also ensure your program doesn't crash if the input file is not found, or if file permissions are incorrect, etc. Docstring, pseudocode, comments, etc. are not required, but may be helpful for partial credit if your code isn't right. [10]
    nums = []
    with open("input.txt") as inFile:
    	for line in inFile:
    		try:
    			nums.append( int(line) )
    		except ValueError:
    			print("not an int:", line)
    with open("output.txt", "w") as outFile:
    	for num in nums:
    		outFile.write("%d\n" % num)