Let's review what we discussed yesterday. A function definition has four parts: a) the keyword def b) the name of the function c) the list of formal parameters (grouped in parens and separated by commas) followed by the colon d) the body of the function (which is a block of statements) Note that there can be variables defined in the body of the function; they are local. The parameters act very much like local variables, initialized when the function is invoked. During the invocation of a function values are being passed to the function in its formal parameters, as arguments. It is there that the famous a = b that we discussed yesterday actually happens. We have primitive types (numbers, booleans) and reference types (everything else). A function works with its formal parameters and any local variables it may define to calculate a result. At the end the function can use the keyword return to indicate the return value. End of summary. Some examples: f(x) = x + 1 In Python we have: def f(x): return x + 1 We could also have: def f(x): result = x + 1 return result Or even: def f(x): x = x + 1 return x In none of these situations will a variable called "result" or "x" be affected in the context of f's invocation. In other words the code below always prints 6, regardless of which one of the three definitions above we use for f. result = 1 x = 2 print result + x + f(x) # [1] Moreover if we printed "result" and "x" after line [1] we would see the values 1, and 2 respectively, in them. So they are unaffected. We also discussed a few other examples including: def fun(x): if x == 0: result = 0 else: # print x # [1] result = x + fun(x-1) # print x # [2] return result We looked at this function with both [1] and [2] commented, with just one of them commented out, and with both lines in. A summary of those examples appear in the lab notes of yesterday. Now let's start writing some meaningful functions: a) write a function to sum up the elements of a list of integers b) write a function that returns a list of a given size that has random numbers in it c) write a function that receives a string, a position in the string, and a character and returns the string with the new character at the given position d) write a function that sorts a list of integers in ascending order e) write a function that returns the list of keys in a dictionary sorted in descending order by their values in the dictionary f) write a function that generates a magic square of size n if n is odd, or returns an error message otherwise. We'll do these things in lab and lecture today.