Sep 27
Homework - generally it's looking pretty good.
Anything you'd like to talk about?
Next assignment - functions, chapter 6 - has been posted
functions
doctests
Discuss how you would make sure a function was
doing what you expect
Suppose you're writing a program that has something
to do with palindromes. One thing you'd need is
to have strings turned around backwards. So what
would a function look like to do that? Turns out
(google "python reverse") that you can reverse
lists easily. And we've seen before that you can
turn strings into lists and vice-versa. So you
play around at the command line and figure this out:
>>> word = "hello"
>>> chars = list(word)
>>> chars
['h', 'e', 'l', 'l', 'o']
>>> chars.reverse()
['o', 'l', 'l', 'e', 'h']
>>> import string
>>> string.join(chars, '')
'olleh'
This is a small specific piece of the larger
problem that you can tuck into a function.
Together with its docs and a test it would look like this:
def reverse_string(word):
""" Reverse a string.
input: a string, e.g. "hello"
output: the string backwards, e.g. "olleh"
>>> reverse_string("Can you hear me?")
'?em raeh uoy naC'
"""
import string
chars = list(word)
chars.reverse()
return string.join(chars, '')
if __name__ == "__main__": # This runs the doctests;
import doctest # just put these 3 lines at the
doctest.testmod() # end if you do this sort of testing.
Put this in "test.py", run it with "python test.py -v".
Also put the wrong thing in the test, and run it with "python test.py".
encode / decode example
An example : encode / decode from before, this time with functions .
- What parts should go into functions?
- What kinds of tests?
- cipher.py
Ideas :
- top-down (look at big picture first) vs bottom-up programming (look at details first)
- test-driven programming can be very useful (write the tests first as a way to see exactly what it's supposed to do)
Class exercise :
- First remember how the program works.
- Then take 5 min to decide on some functions.
- For each function, you typically need to consider both
- the interface (how you use it, inputs & outputs), and
- implementation (how to make it work)
I've attached what I wrote in class as
new_cipher.py; see below. (However,
it hasn't been tested and probably has typos.)
Here's a start of a top-down approach to the cipher problem :
"""
cipher_functions.py
"""
def get_user_input():
# fill in docs & test
return ('wwww', 'kkkk') # FIXME
def translate(word, key):
# fill in docs & test
return '????' # FIXME
def main():
print "-- cipher --\n"
(word, key) = get_user_input()
encoded = translate(word, key)
print "'%s' encrypted is '%s'" % (word, encoded)
# TODO: put stuff to run doctest here
main()
book example
- inputs?
- outputs?
- side effects?
- tests?
- docs?
default values in function arguments
def do_something(size, color="white"):
# code goes here
print "size, color = %i, %s" % (size, color)
do_something(3, "blue") # this is OK
do_something(4) # also OK; color defaults to "white"
do_something() # *not* OK; 0 args gives error
Args with defaults may only go on the *end* of the argument list ... otherwise the later ones (required) imply that the earlier ones are also required.
Note that this is a python-specific syntax.
multiple return values
def get_stuff():
return 1, "hey"
# And now use it
a, b = get_stuff()
# "Tuples" in python
other bells and whistles
Less used, and can be safely ignored on a first pass through python.
But for those who like the tricky corners...
def two_or_more_args(a, b, *c):
print "a = '" + str(a) + "'"
print "b = '" + str(b) + "'"
print "c = '" + str(c) + "'"
# and now call it.
two_or_more_args(3, "hey") # a=3, b="hey", c=[]
two_or_more_args(3, "hey", 4, "there") # a=3, b="hey", c=[4, "there"]
depending on time
... start "conditionals" (chapters 7 and 8):
value = input("What is the number? (1 to 10) ")
if value < 1 or value > 10 :
print "Oops: your number was too big or too small."
print "Your number is %i" % number
Discuss flowcharts.
Discuss comparison operators.
Coming: boolean variables.