WEEK05: functions 
---------------------------------------------------------------
 W: review functions, scope


REVIEW of FUNCTIONS:

** listfunctions.py

def main():

  L = [20,-13,200,180,370,456,99]
  print L

  numoutofrange = outOfRange(L, 0, 255)
  print "num out of range %d-%d: %d" % (0, 255, numoutofrange)

##############################################################

def outOfRange(mylist, low, high):
  """figures out how many items in list are out of range"""

  counter = 0
  for i in mylist:
    if i < low or i > high:
      counter = counter + 1

  return counter

##############################################################

main()

 - how many parameters does the outOfRange function have?
 - what does it return?
 - in the call to outOfRange() in main, what are the arguments?


NOTE: ALL FUNCTIONS YOU WRITE NEED A """COMMENT""" RIGHT UNDER
      THE def function(): LINE!!!!!

PYTHON TUTOR: http://www.pythontutor.com/

 - copy and paste the above code into the python tutor and
   run it (Visualize Execution)
 - notice how the scope of each variable is "local" to each
   function (you can't use "L" in outOfRange -- there is no
   variable "L" in outOfRange)

 - think about how data is passed back and forth from main to functions:

     main        function
     ----        --------

   arguments  -->

         <--   return values


YOUR TURN:

 - add a sumOfList() call and function to the above code, so
   we can do this in main:

  total = sumOfList(L)
  print "the sum of that list is: %d" % (total)

##############################################################
def sumOfList(thelist):
  """sum and return all elements of list"""

  total = 0
  for num in thelist:
    total = total + num

  return total
##############################################################


YOUR TURN: 

 - add a maxOfList() function to the above code
   (this one is a bit harder!!)

  mymax = maxOfList(L)
  print "the max of that list is: %d" % (mymax)

##############################################################
def maxOfList(mylist):
  """find and return largest value in list"""

  biggestsofar = mylist[0]
  for num in mylist:
    if num > biggestsofar:
      biggestsofar = num

  return biggestsofar
##############################################################


 - when you add functions, make sure you test all cases!