knerr cs21 notes...

back to schedule

WEEK05: functions and lists
---------------------------------------------------------------
 M: who,what,when,where,and why of functions...

LAB4: due Tuesday

SPECIAL READING NOTE: section 6.2 (Incremental Development) from
	the Downey book is a *must* read!

WHY FUNCTIONS:

 - make code more readable
 - make code easier to maintain and debug
 - good for code reuse
 - necessary for large/complex programs

 For example: you are working on a program to draw a face.
 What would you do if you had to draw many faces? Wouldn't
 it be nice call a drawFace function, and give it a size 
 and position, like this:

   drawFace(position, size, color, window)

 Now you can call that function over and over, giving it
 different positions and sizes!

FUNCTION DETAILS:

 - take a look at /home/jk/inclass/example_funcs.py, written by Tia

 simple functions have no parameters and don't return anything:

def print_greeting():
  print "Hello there, welcome to my program"

 other functions have parameters and return something to main:

def count_letters(string, letter): 
  count = 0
  for ch in string:
    if ch == letter:
      count = count + 1

  return count 

 in the above count_letters function, whatever string and letter
 are, it will count the number of times the letter is in the string
 and return that number to the caller.

 calling it like this:

   c = count_letters("this is fun", "i")

 would count the number of i's in the string, returning a 2.

FUNCTION TERMINOLOGY:

 In the above example, "this is fun" and "i" are arguments.
 
 Inside the count_letters function, the argument "this is fun" is
 assigned to the parameter string (and the argument "i"
 is assigned to the parameter letter).

 All of the variables in count_letters are local in scope, meaning
 they only exist when the function is being executed. Once the function
 is finished, count, ch, letter, and string are gone.

 Functions that return something to the calling program should return
 the same kind of thing every time. For example, count_letters always
 returns an integer.

 Python allows functions to return more that one thing, but that's
 usually not a good idea (and many other languages don't allow this).
 Try to make your functions do just one thing.

YOUR TURN:

  - see if you can write a function that takes two integers,
    then returns the square of the biggest int

  - if you have time, see if you can write a function that, given
    a point, size, and window, draws a circle (or square or star)