Lecture 5.1_ Functions.pdf
Document Details
Uploaded by GenerousChrysoprase
La Trobe University
Tags
Full Transcript
Lecture 5.1 Functions Topic 5 Intended Learning Outcomes ◎ By the end of week 5 you should be able to: ○ Define and call functions to reuse sections of code, ○ Define custom types of objects with classes, and ○ Understand how references work, and the difference between mutable and immutable objec...
Lecture 5.1 Functions Topic 5 Intended Learning Outcomes ◎ By the end of week 5 you should be able to: ○ Define and call functions to reuse sections of code, ○ Define custom types of objects with classes, and ○ Understand how references work, and the difference between mutable and immutable objects. 2 Lecture Overview 1. Function Calls 2. Writing Functions 3. Parameters, Scope, and Return Values 3 1. Function 4 What is a Function? 5 What is a Function? 6 What is a Function? 7 What is a Function? 8 Function Calls ◎ To run the code in a function, you must call the function. ◎ We have already been using function calls! Here are some that should look familiar: ○ print('Hello') ○ input('Enter your age: ‘) ○ range (1,6) 9 Arguments ◎ The inputs supplied to a function are called arguments. ◎ Any kind of expression can be used as an argument: ○ Literals (e.g. type(65.3)), ○ Variables (e.g. str(temperature)), or ○ Complex expressions (e.g. print('$' + str(x * 2))). ◎ Multiple arguments are separated using commas. 10 Things Functions Can Do ◎ A function can cause an effect. ○ For example, the print function causes an output message to be displayed. ◎ A function can compute and return a result. ○ For example, the str function* (str(x * 2)) converts its argument to a string and returns the result. 11 Check Your Understanding Q. What is the second argument in this function call? print('I, Jimbo, am', 18, 'years old') 12 Check Your Understanding Q. What is the second argument in this function call? print('I, Jimbo, am', 18, 'years old') A. 18 is the second argument. ◎ print is the function name, not an argument. ◎ 'I, Jimbo, am' is the first argument. ○ These commas are part of the string. ◎ 'years old' is the third argument. 13 Pythom Functions 14 Built-in Functions import builtins print (dir(builtins)) 15 Built-in Functions 16 Built-in Functions 17 2. Writing Functions - User-Defined Functions 18 Pythom Functions: User-Defined Functions 19 Writing a Function: User-Defined Functions 20 Writing a Function: User-Defined Functions 21 Writing a Function: User-Defined Functions 22 Writing a Function: User-Defined Functions 23 Writing a Function: Control Flow ◎ When a function is called, control flow jumps to the first statement in the function. ◎ When the function finishes, control flow is returned to the place that the function was called from. ◎ The statements in a function are not executed when the function is defined. 24 Example: Control Flow 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() ◎ Let's look at the control flow for this program. ◎ The statements within the tick function are executed with each function call. print('Goodbye!') 25 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() print('Goodbye!') 26 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? print('Goodbye!') 27 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? print('Goodbye!') 28 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick print('Goodbye!') 29 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock print('Goodbye!') 30 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock print('Goodbye!') 31 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock print('Goodbye!') 32 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock Tick print('Goodbye!') 33 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() Who am I? Tick Tock I am a clock Tick Tock print('Goodbye!') 34 Example: Control Flow Output: 1 2 3 4 5 6 7 8 def tick(): print('Tick') print('Tock') print('Who am I?') tick() print('I am a clock') tick() print('Goodbye!') Who am I? Tick Tock I am a clock Tick Tock Goodbye! 35 Don't Repeat Yourself ◎ In software development, there's a good practice called DRY (don't repeat yourself). ◎ DRY code avoids code duplication (writing similar code multiple times). ◎ Functions are an effective tool for producing DRY code. 36 Example: Code Duplication 1 2 3 4 5 6 water = 0.712 print('Covered in water:') print(str(water * 100) + '%') land = 1 - water print('Covered in land:') print(str(land * 100) + '%') ◎ Lines 3 and 6 have the same purpose: to display a percentage. ◎ Problems: ○ It is cumbersome to copy/paste. ○ Changing the way percentages are displayed requires multiple edits. ◎ This is error-prone. 37 Example: Code Duplication 1 2 3 4 5 6 water = 0.712 print('Covered in water:') print(str(round(water*100))+'%') land = 1 - water print('Covered in land:') print(str(round(land*100))+'%') ◎ Here we had to edit 2 lines to print percentages as round numbers. ◎ In a larger program, many more edits could be required. ○ It's easy to forget one, or to make a mistake. 38 Example: DRY Code with a Function 1 2 3 4 5 6 7 8 9 def print_percent(x): print(str(round(x*100))+'%') water = 0.712 print('Covered in water:') print_percent(water) land = 1 - water print('Covered in land:') print_percent(land) ◎ Lines 1--2 define the print_percent function. ○ The function has one parameter, x. ◎ Lines 6 and 9 call the function. ○ The code in print_percent will be executed with x set to the argument value. 39 Check Your Understanding Q. How many times will the shown program print output? 1 2 3 4 5 6 7 def funky_func(): for i in range(3): print('Groovy!') funky_func() if 2 + 2 == 5: funky_func() funky_func() 40 Check Your Understanding Q. How many times will the shown program print output? A. 6 times. ◎ Each time funky_func is called, 'Groovy!' is printed 3 times. ◎ funky_func is called twice (lines 4 and 7). ○ Not called from line 6 since the if statement condition is false. 1 2 3 4 5 6 7 def funky_func(): for i in range(3): print('Groovy!') funky_func() if 2 + 2 == 5: funky_func() funky_func() 41 3. Parameters, Scope, and Return Values 42 Parameters and Arguments. ◎ Parameters are function input variables declared as part of defining a function. ○ A function can have zero, one, or many parameters. ○ Act like "placeholders". ◎ Arguments are the values assigned to parameters when calling a function. ○ A function must receive one argument per parameter. 43 Example: Parameters and Arguments 1 2 3 4 def print_product(x, y): print(x * y) print_product(3, 5) ◎ x and y are parameters. ◎ Line 1: "define a function called print_product with two parameters, x and y". 44 Example: Parameters and Arguments 1 2 3 4 def print_product(x, y): print(x * y) ◎ 3 and 5 are arguments. print_product(3, 5) ◎ Line 4: "call print_product with 3 as the first argument and 5 as the second argument". ◎ The order matters---x will take the value of 3, and y will take the value of 5. 45 Function Default Arguments ◎ A default argument is a value given to a parameter when no argument is explicitly provided in the function call. ◎ You can specify default arguments as part of the function definition. 46 Function Default Arguments 47 Example: Default Arguments def print_ticket(age, max_child_age=12): if age <= max_child_age: print('Child') else: print('Full fare') print_ticket(5) #=> Child print_ticket(15) #=> Full fare print_ticket(15, 18) #=> Child 48 Default Arguments Beware! Once you specify a default argument for one parameter, all parameters which come after it must also have default arguments. >>> def do_something(a, b=1, c): ... pass ... File "<stdin>", line 1 SyntaxError: non-default argument follows default argument 49 Named Arguments ◎ Arguments can also be specified by name. ◎ These kinds of arguments are called named arguments (or keyword arguments). def divide(num, denom): print(num / denom) divide(5, 2) #=> 2.5 divide(denom=2, num=5) #=> 2.5 divide(5, denom=2) #=> 2.5 divide(num=5, 2) #=> Error ◎ The order of named arguments doesn't matter. ◎ All named arguments must appear after positional arguments. 50 Named Arguments ◎ In most cases you will not need to use named arguments. ◎ If you think that they will make your code more understandable, go ahead and use them. ◎ Occasionally you will encounter functions that do actually require named arguments. ○ We won't see many in this subject. ○ It will be pointed out to you when we do. 51 Example: Variable Scope def double_number(x): y = x * 2 double_number(5) print(y) Traceback (most recent call last): File "scope.py", line 5, in <module> print(y) NameError: name 'y' is not defined ◎ The code outside of double_number can't "see" x and y. ○ It's as if those variables don't exist. ◎ As a result, the line containing the print statement will raise an error. 52 Return Values ◎ If variables created inside a function aren't accessible outside it, then how do we get the result of a calculation performed inside the function? ○ Answer: use a return value. ○ A function can return one or more values using the return statement. 53 Return Values. ◎ A function can have a return value, which is a value from inside the function which is returned to the caller of the function. ◎ The function call will evaluate to the returned value. ◎ We've actually already used several functions with return values. ○ e.g. abs(-3) evaluates to 3 (its return value). ◎ We can specify which value is returned from a function by using a return statement. 54 Return Statements ◎ A return statement can only be used inside a function. ◎ In Python, a return statement consists of the return keyword followed by a value to be returned. ○ return 'A cool result' ○ return x + 1 ◎ When a return statement is encountered, function execution finishes and the specified value is returned to the caller. 55 Example: Return Statement def double_number(x): y = x * 2 return y z = double_number(5) ◎ The value of variable y is returned from function double_number. print(z) ◎ This means that the expression double_number(5) will evaluate to 10. 56 Example: Return Statement 57 Finishing Function Execution Early ◎ After a return statement is encountered, the function finishes immediately. ○ Statements which appear after the return statement will not be executed. ○ This is similar to continue and break in loops. ◎ The return keyword can be used by itself to finish a function without also returning a value. 58 Check Your Understanding Q. What is the output of the shown program? 1 2 3 4 5 6 def do_something(n): if n < 0: return 0 return n ** 2 print(do_something(-4)) 59 Check Your Understanding Q. What is the output of the shown program? A. 0. ◎ do_something is called with -4 as the first argument (so n is 4). ◎ -4 is less than 0, so 0 is returned. ◎ Line 4 is not reached. 1 2 3 4 5 6 def do_something(n): if n < 0: return 0 return n ** 2 print(do_something(-4)) 60 Summary 61 In This Lecture We... ◎ Used function calls to execute pieces of existing code. ◎ Created our own functions to enable code reuse. ◎ Learnt the difference between arguments and parameters. ◎ Discovered how return statements can be used to get results out of a function. 62 Next Lecture We Will... ◎ Learn about another construct for tackling repetition in code: objects. 63 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 64