Sep 25
Discuss the homework. Questions? Comments?
We did the rectangle draw and file input
problem in class; see the attached files.
Here's another animation example :
ball_arc.py
(Note various types of docs within the file.)
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]'
- This is one of the key ideas of the semester
- It's a "mini program"
Functions can take "arguments".
- Go over process of invoking a function, and what happens to the values "passed in" to a function.
Functions let you avoid repitition.
- Happy birthday example.
- Look over previous graphics programs, and do same.
Functions break a program into bite-sized chunks.
- Each with own documentation.
- Each with own tests. (More on this in a bit.)
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 what a "side effect" is.
- And why they're bad: hard to tell what function does, and so hard to debug.
Discuss "Global" vs "Local" variables, and "scope".
- And that different programming languages behave differently in how they treat them.
- Including what happens to passed arguments that are modified.
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: