- Fill in the blank: [6]
- In software development, the document that describes the functionality
you intend to deliver to the client is called the
specifications________________.
- When we wish to print() an object to the console, which method
of the object does Python invoke? __str__()_______________.
- In a Python class, the __init__() method is the special
method called the constructor or initializer____________________.
- The Python method on file objects that sets the file pointer
(location within the file) is called seek()__________
- What English part of speech should a method name be?
verb___________
- Let myList = [ 9, 8, 7, 6 ]. What is myList[1:3]?
[8, 7]_____________
- 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.
-
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.
-
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 '
- 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.
- 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
- 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.
-
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.
- Define or describe each of the following terms in object-oriented
programming: [5]
- Class: a user-defined container type
- Instance: an object; instances are to classes as variables are to
types
- Attribute: a variable or method belonging to an object
- Method: a function/procedure belonging to an object
- Constructor/initializer: the special method which is called when
an object is instantiated
- 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.
- 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.
- 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)
- 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)