Overview
Teaching: 10 min Exercises: 15 minQuestions
How can I create my own functions?
Objectives
Explain and identify the difference between function definition and function call.
Write a function that takes a small, fixed number of arguments and produces a single result.
Correctly identify local and global variable use in a function.
Correctly identify portions of source code that will be displayed as online help, and in particular distinguish docstrings from comments.
Write short docstrings for functions.
def
with a name, parameters, and a block of code.def
.def print_greeting():
print('Hello!')
print_greeting()
Hello!
def print_date(year, month, day):
joined = str(year) + '/' + str(month) + '/' + str(day)
print(joined)
print_date(1871, 3, 19)
1871/3/19
()
contains the ingredients for the function
while the body contains the recipe.return
.return ...
to give a value back to the caller.return
occurs:
def average(values):
if len(values) == 0:
return None
return sum(values) / len(values)
a = average([1, 3, 4])
print('average of actual values:', a)
2.6666666666666665
print('average of empty list:', average([]))
None
return
a value automatically returns None
.result = print_date(1871, 3, 19)
print('result of call is:', result)
1871/3/19
result of call is: None
Definition and Use
What does the following program print?
~~~ def report(pressure): print(‘pressure is’, pressure)
print(‘calling’, report, 22.5)
Find the First
Fill in the blanks to create a function that takes a list of numbers as an argument and returns the first negative value in the list. What does your function do if the list is empty?
def first_negative(values): for v in ____: if ____: return ____
Order of Operations
The example above:
result = print_date(1871, 3, 19) print('result of call is:', result)
printed:
1871/3/19 result of call is: None
Explain why the two lines of output appeared in the order they did.
Calling by Name
What does this short program print?
def print_date(year, month, day): joined = str(year) + '/' + str(month) + '/' + str(day) print(joined) print_date(day=1, month=2, year=2003)
- When have you seen a function call like this before?
- When and why is it useful to call functions this way?
Key Points
Break programs down into functions to make them easier to understand.
Define a function using
def
with a name, parameters, and a block of code.Defining a function does not run it.
Arguments in call are matched to parameters in definition.
Functions may return a result to their caller using
return
.