Lecture 12 + pseudo Lab

posted Feb 20, 2013, 6:06 AM by Samuel Konstantinovich   [ updated Feb 20, 2013, 6:06 AM ]
Goal: Write Python functions that return values

So far you wrote python functions that print values. Usually we don’t print values when making calculations, in fact most functions do calculations, and let some other function decide what should be printed. A function that returns a value is MUCH more flexible than a printing function. Here is an example:

#define a function
def printFoo(a,b):
  print a+b
#you can only use the function this way:
printFoo(2,3)


#define a return function
def foo(a,b):
  return a+b

#you can use this function many ways:
  • print  foo(2,3)  #this is the same as what the old function does

#here are some things that cannot be done if you print:
  • x = foo(2,3)  #you can assign the result to a variable
  • x = 1+foo(2,3) #you can use it in a calculation
  • x = abs( foo(1,2) )  #you can use foo as a parameter to another function (or itself)
#all of the above examples can be printed instead of assigning them. This makes returned values preferred over printing.

Write the following Practice functions from the coding bat website:
http://codingbat.com/python/Warmup-1

sleep_in
diff21
near_hundred
parrot_trouble
pos_neg

If you make a codingBat account, then you don't have to save the work on your computers!
Comments