120 likes | 189 Views
Functions. Victor Norman CS104 Calvin College. Reading Quiz. Counts toward your grade. Function Defn is an Abstraction. A bstracts and names lines of code. can be called repeatedly can take arguments. Consider: y = sin(x).
E N D
Functions Victor Norman CS104 Calvin College
Reading Quiz • Counts toward your grade.
Function Defn is an Abstraction • Abstracts and names lines of code. • can be called repeatedly • can take arguments. Consider: y = sin(x). • Takes a value x, runs the sin function on it, producing a result that y is made to refer to.
Function Def’n vs. Call • Definition: deffuncname(param_names): statements to execute when funcname is called • Call: y = int(input(“Enter your age: “)) result = funcname(y) • How many function calls in this code? • Call must provide the same # of values as the function definition requires.
Non-fruitful Functions • Non-fruitful functions produce no value for the caller. • Just execute their statements • Not useful unless they do something like print something or make the robot move, etc. • Useful for turtle graphics. E.g., defdrawSquare(size): code here to draw a square of size. Returns nothing.
Fruitful Function • Computes a value and returns it to the caller. def squared(val): newval = val * val return newval • Return sends value back to the caller and exits the code in the function. • Function will exit the code anyway at the end of the function.
Clicker Questions Given this code: 1 def foo(x): • return x + 1 • def bar(x, y): • t = foo(x) • return t + y • defbaz(z): • t = bar(z, z) • return foo(t) • n = 3 • res = baz(n) • print(res)
Parameters and Local Variables • Parameters hold the *values* being passed in in the function call. • Both are defined only within the code of the function. • That is their scope or lifetime. • They can be altered within the code. • Can think of them as "temporary variables" -- places to hold values while you work on computing the result or doing the work.
Return Statement • Computes the result to be sent back to the caller. • Exits the code in the function, even if there is code after it. • E.g., def computeIt(x, y, z): w = x + y / z return w print("Done!") # never executed
Return vs. print() • Printing a value in a function does not return it. • print sends charactersout to the output “stream” – i.e., the screen. • To send a value back to the caller you must use return <val>
Clicker Questions Given this code: 1 defbeatHope(i): • i = i * i • print("Let's beat Hope", i, "times") • print(beatHope(3))
Assignment • Do ~21 questions from the Functions section in CodeLabbefore lab on Thursday. • Study for test on Thursday.