Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?

Similar presentations


Presentation on theme: "Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?"— Presentation transcript:

1 Functions CMSC 201

2 Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?

3 Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right? myList = [1, 2, 3, 4] largest = myList[0] for item in myList: if item > largest: largest = item print(largest)

4 Motivation What if we want to do this multiple times in our program? We don’t want to rewrite the code multiple times. What variables do we need access to in order to find the maximum of a list? What piece of information will we have when we’re done?

5 Functions We can create a function to find the maximum whenever we want to! Think of a function as a machine that you stick some input into, and your results pop out. So for our example, our listMax function would have to have the list go in, and would spit the maximum back out. myList Functio n code maximum

6 Vocab The inputs for a function are called arguments. A function can have as many arguments as it needs to fulfill its purpose. For example, a function that counts the number of times some number x appears in a list would need the number x, as well as the list. The result of a function is called the return value. In the example above, the return value would be the number of times x appears.

7 You’ve Called Functions Before! print("Hello") The thing you want to print. Print doesn’t return anything! It has a side effect, but doesn’t give anything back.

8 You’ve Called Functions Before! width = int(input("Enter the box width: ")) “Please enter the box width: “ is the argument, the prompt to the user. The return value of the int function is stored in width.

9 You’ve Called Functions Before! someVar = range(0, 40) This function requires two arguments, the start and end of the range you want. The return value of this function is stored in someVar (in this case, a list of the numbers between 0 and 40)

10 Functions So in general, when we want to call a function, we use the following format: result = functionName(arg1, arg2)

11 Writing a Function That’s great, but where do functions come from?

12 Making a Function Say we have the following code to find the maximum of a list: myList = [1, 2, 3, 4] largest = myList[0] for item in myList: if item > largest: largest = item And we want to be able to use it over and over.

13 Making a Function def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest def is the keyword for defining a function in python Max is the name of the function myList is the list we are finding the max of. ‘return’ is how the function knows what to send back to the main program.

14 The Life Cycle of a Function someList = [1, 2, 3, 4] maxNum = max(someList) def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest someList gets renamed my list and this code is run Whatever was in max gets stored in maxNum

15 Calling Functions Multiple Times otherList = [8, 9, 10] someList = [1, 2, 3, 4] maxNum = max(someList) otherNum = max(otherList) def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest someList gets renamed myList and this code is run Whatever was in largest gets stored in maxNum def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest Next time, otherList gets copied A different largest gets copied into otherNum

16 Note In the last example, when someList gets put into the function, it gets renamed as whatever parameter that function expects. So someList becomes myList. Also, a function only knows about the parameters it’s given! Variables from the original program don’t carry over!

17 Scope someList = [1, 2, 3, 4] b = 6 maxNum = max(someList) def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item b = 10 return largest Even though the original program has a variable named b, this function doesn’t know about it!

18 Scope A name is considered defined in a function if there is an assignment to that name anywhere within the body of the function. In Python, this assignment creates a binding of the name to a value. The parts of a program where this binding is directly accessible is the scope that binding.

19 Scope (cont'd) The same name can be used in different scopes and different name spaces. Python has 4 scopes local scope scope of enclosing functions global built-in Python will look for bindings in this order.

20 Scope (cont'd) In a function, names defined in the function have local scope. These are usually called local variables. In a function, parameters are also local. Names defined outside of any function have global scope. These are usually called global variables. Local and global variables can have the same name, which can lead to much confusion.

21 Scope (cont'd) To avoid confusion between local and global variables with the same name: Use different names (not always convenient). Don't use global variables (not allowed in CMSC201, anyway). Initialize your local variables at the beginning of each function to make it obvious that they are local.

22 Exercise Write a function called average that returns the average of a list. Then show how you would call this function.

23 Exercise Write a function called average that returns the average of a list. Then show how you would call this function. def average(myList): sum = 0 for item in myList: sum = sum + item return sum/len(myList) result = average(myList)

24 Multiple Parameters In order to make a function with multiple parameters, you can simply say: def someFunction(parameter1, parameter2): You would call someFunction as follows: someFunction(10, 20) Parameter1 would have the value of 10, and parameter2 would have the value of 20. The parameters go in order.

25 The Life Cycle of a Function a = 10 b = 15 result = sum(a, b) def sum(num1, num2): return num1 + num2 a and b are copied into num1 and num2 respectively. num1+num2 gets returned into result.

26 Exercise Write a function that takes two lists as arguments and finds the sum of both lists. For example: listA = [1, 2, 3] listB = [3, 4, 5] result = sumTwoLists (listA, listB) print(result) Prints: 18

27 Exercise Write a function that takes two lists as arguments and finds the sum of both lists. def sumTwoLists(list1, list2): sum = 0 for item in list1: sum = sum + item for item in list2: sum = sum + item return sum

28 Exercise Note: Functions can call each other! def sumTwoLists(list1, list2): return sum(list1) + sum(list2) def sum(list1): sum = 0 for item in list1: sum = sum + item return sum

29 Exercise Note: Functions can call each other! myList = [1, 2, 3] otherList = [4, 5, 6] result =sumTwoLists(myList, otherList) def sum(list1): sum = 0 for item in list1: sum = sum + item return sum def sumTwoLists(list1, list2): return sum(list1) + sum(list2)

30 Even More Arguments Three arguments work the exact same way: someFunction(arg1, arg2, arg3) def someFunction(arg1, arg2, arg3): #code goes here

31 Return Statements A function can have multiple return statements! Imagine a function that just takes two numbers and returns the larger. def max(number1, number2): if number1 > number2: return number1 else: return number2 Either return statement ends the program.

32 Return Statements def max(number1, number2): if number1 > number2: return number1 else: return number2 a = 5 b = 10 result = max(a, b) Only one of these values gets returned!

33 Return Statements A return statement immediately stops the function. This code doesn’t make sense! Line-3 will never be reached, because the return statement ends the function! def someFunction(arg1): line-1 line-2 return someVariable line-3

34 Exercise Write a function called factorial that finds the factorial of a single argument.

35 Exercise Write a function called factorial that finds the factorial of a single argument. def factorial(num): result = 1 for count in range(1, num+1): result = count * result return num

36 Notes The name of the variables in the functions have nothing to do with anything outside of the function. Feel free to name arguments whatever you like, as long as it makes sense. Never name a variable and a function the same thing. This will confuse python terribly.

37 The Main Function From now on, we will be putting our code in a special function known as main. Main is always called first whenever a program is run. def main(): # All of you code should be here def someOtherFunctions(): # More code main()

38 When To Create Functions We use functions to organize our code. From now on in this class, we will use functions whenever possible. You should break your code up into functions when: You have a clear, self contained process that can be isolated from the code around it. You have an operation that may need to be performed multiple times. It will simplify the readability of your code.


Download ppt "Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?"

Similar presentations


Ads by Google