Intro to
Programming
with Python

Fall 2010
course
navigation

sep 28

chap 6 : 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)
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

... depending on time :
First, discuss python function documentation conventions:
Discuss attached doctest_example.py
http://cs.marlboro.edu/ courses/ fall2010/python/ notes/ sep_27
last modified Tuesday September 28 2010 10:13 am EDT

attachments [paper clip]

     name last modified size
   ball_arc.py Sep 27 2010 3:30 pm 3.28kB    doctest_example.py Sep 27 2010 2:08 pm 1.51kB    happy_birthday.py Sep 28 2010 10:12 am 539B