Transcript Functions

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?
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]
max = myList[0]
for item in myList:
if item > max:
max = item
print(max)
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?
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.
myList
Functio
n
code
maximum
So for our example, our listMax function would have to
have the list go in, and would spit the maximum back out.
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.
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.
You’ve Called Functions
Before!
width = int(input(“Please 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.
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)
Functions
So in general, when we want to call a function, we use the
following format:
resultValue = functionName(argument1,
argument2)
Writing a Function
That’s great, but where do functions come from?
Making a Function
Say we have the following code to find the maximum of a
list:
myList = [1, 2, 3, 4]
max = myList[0]
for item in myList:
if item > max:
max = item
And we want to be able to use it over and over.
Making a Function
Max is the name of the
function
def is the
keyword for
defining a
function in
python
myList is the list we are finding
the max of.
def max(myList):
max = myList[0]
for item in myList:
if item > max:
max = item
return max
‘return’ is how the function knows
what to send back to the main
program.
The Life Cycle of a Function
someList = [1, 2, 3, 4]
someList gets renamed my
list and this code is run
maxNum = max(someList)
def max(myList):
max = myList[0]
for item in myList:
if item > max:
max = item
return max
Whatever was in max gets
stored in maxNum
Calling Functions Multiple
Times
otherList = [8, 9, 10]
someList = [1, 2, 3, 4]
someList gets renamed
myList and this code is run
maxNum = max(someList)
def max(myList):
maxNum = myList[0]
Whatever was in max gets
stored in maxNum
for item in myList:
if item > maxNum :
maxNum = item
return maxNum
Next time,
otherList gets
copied
otherNum = max(otherList)
def max(myList):
maxNum = myList[0]
A different max gets
copied into otherNum
:
for item in myList:
if item > maxNum
maxNum = item
return maxNum
Note
In the last example, when someList gets put into the
function, it gets renamed as whatever argument that
function expects. So someList becomes myList.
Also, a function only knows about the arguments it’s
given! Variables from the original program don’t carry
over!
Scope
someList = [1, 2, 3, 4]
b = 6
maxNum = max(someList)
def someFunction(myList):
max = myList[0]
Even though the
original program
has a variable
named b, this
function doesn’t
know about it!
for item in myList:
if item > max:
max = item
b = 10
return max
Scope
This concept is called scope.
The variables given to a function as arguments and the
variables defined inside the function constitute the scope
of the function.
Exercise
Write a function called average that returns the average of
a list. Then show how you would call this function.
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)
Functions With 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 always go in order.
The Life Cycle of a Function
a = 10
b = 15
result = sum(a, b)
a and b are copied into num1
and num2 respectively.
def sum(num1, num2):
return num1 + num2
num1+num2 gets returned
into result.
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
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
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
Exercise
Note: Functions can call each other!
myList = [1, 2, 3]
otherList = [4, 5, 6]
def sumTwoLists(list1, list2):
return sum(list1) + sum(list2)
result =sumTwoLists(myList, otherList)
def sum(list1):
sum = 0
for item in list1:
sum = sum + item
return sum
Even More Arguments
Three arguments work the exact same way:
someFunction(arg1, arg2, arg3)
def someFunction(arg1, arg2, arg3):
#code goes here
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.
Return Statements
a = 5
b = 10
result = max(a, b)
def max(number1, number2):
if number1 > number2:
return number1
else:
return number2
Only one of these values
gets returned!
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
Exercise
Write a function called factorial that finds the factorial of a
single argument.
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
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.
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()
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.