Introductory Programming Fall 2004 For next time you should: 1) Read chapter 3 of the Olinux manual, but don't do Section 3.10: Practice!!! 2) Start Homework 3 Functions --------- You can define your own functions, and then call them. def twice(s): print s, s twice('allen') You can run this as a script, or type it in to the interpreter. In the interpreter, it will look like >>> def twice(s): ... print s, s ... >>> twice('allen') allen allen The ... means that Python is waiting for you to finish something you have started, in this case a function definition. Function syntax --------------- function def is an example of a compound statement 1) header ending in : 2) indented body By convention, indentation is 4 spaces. End of body marked by an outdented line. def twice(s): print s, s def fourtimes(s): twice(s) twice(s) A function definition doesn't DO anything except: 1) create a function object 2) create a name that refers to the object Expressions as arguments ------------------------ Any expression can be used as an argument 1) A simple value len('allen') log(10) 2) A variable sin(pi) twice(s) 3) An expression with operands and operators sin(pi/4) first = 'allen' last = 'downey' fourtimes(first + ' ' + last) make some errors ---------------- Try out the following and see what goes wrong: 1) leave off the colon : def fun() x = 1 2) mess up the indentation def fun(): x = 1 y = 1 def fun(): x = 1 y = 1 3) call a function with the wrong number of arguments len('allen', 'downey') 4) call something that is not a function x = 5 x(17)