Intro to
Programming
(with Python)

Fall 2015
course
navigation

functions - Tue Sep 29

homework

Discuss the homework. Questions? Comments?
An example of the rectangle draw and file input problem is in bar graph - we'll discuss that, as it's the one folks typically have questions on.

chap 6 : functions

OK, on to new material : functions.
Here's an example :
# Define a function. def print_info(x): print " " + str(type(x)) + " has value '"+ str(x) + "'" # Call it several times. print_info(3.2) print_info('a') print_info("alpha") print_info([1,2,3])
Running that gives <type 'float'> has value '3.2' <type 'str'> has value 'a' <type 'str'> has value 'alpha' <type 'list'> has value '[1, 2, 3]'
Functions can take "arguments".
Functions let you avoid repitition.
Functions break a program into bite-sized chunks.
Functions may "return" a value. def double(x): return 2*x def print_double(x): print "Twice " + str(x) + " is " + str(double(x)) for i in range(4): print_double(i)
Discuss the difference between "returning" something and "printing" it. (And how that difference is less clear when working at the python prompt.) This is important, and in the past I have sometimes seen it confuse people.
Functions may have side effects ... but you should usually avoid that.
Discuss "Global" vs "Local" variables, and "scope".
What does this do?
# Define a global variable. a = 6 # Define a function that alters its argument. def increment_argument(x): x = x + 1 # Does it work? print "a is " + str(a) increment_argument(a) print "now a is " + str(a)
How about this?
# Define a global variable. a = ["zero", "one"] # Define a function that alters its argument. def alter_array(x): x[1] = x[1] + " ... changed" # Does it work? print "a is " + str(a) alter_array(a) print "now a is " + str(a)
What's the difference?
Go over examples from previous graphics programming and/or homework, adding functions in to make the code shorter and clearer.

documentation and tests

From Dijkstra :
... depending on time :
First, discuss python function documentation conventions:
Discuss doctest_example.py.
http://cs.marlboro.edu/ courses/ fall2015/python/ notes/ Sep_29
last modified Monday September 28 2015 8:20 am EDT