Overview
Teaching: 15 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.
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 (via Twitter).return
statement.return ...
to give a value back to the caller.return
occurs:
def average(values):
if len(values) == 0:
return None
output = sum(values) / len(values)
return output
a = average([1, 3, 4])
print('average of actual values:', a)
2.6666666666666665
print('average of empty list:', average([]))
None
None
return
a value automatically returns None
.def greeting(message):
print(message)
result = greeting("Hello World!)
print('The result of the call to greeting is:', result)
Hello World!
The result of the call to greeting is: None
Definition and Use
What does the following program print?
def report(pressure): print('The pressure is', pressure) report(22.5)
Order of Operations
The following code is written given the function in the previous example
result = report(22.5) print('result of call is:', result)
The output is:
The pressure is 22.5 result of call is: None
Explain why the two lines of output appeared in the order they did.
Encapsulation
Fill in the blanks to create a function that calculates the area of a circle
import math def area_of_circ(____): area = math.______ * _____ ** 2 return ____
Hint
The formula for area is pi * radius ^ 2
Solution
import math def area_of_circ(radius): area = math.pi * radius ** 2 return area
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)
- Why do you think it’s okay to call the arguments in a different order like this?
- When and why is it useful to call functions this way?
Encapsulating a for-loop
Write a function that sings ‘99 bottles of beer on the wall’, for however many verses the singer wishes to sing it
Solution
def bottles_of_beer(num_bottles): for bottle in range(1, num_bottles): print(bottle, "bottles of beer on the wall") print(bottle, "bottles of beer") print("Take one down and pass it around") print(bottle - 1, "bottles of beer on the wall\n") bottles_of_beer(4)
Identifying Syntax Errors
- Read the code below and try to identify what the errors are without running it.
- Run the code and read the error message. Is it a
SyntaxError
or anIndentationError
?- Fix the error.
- Repeat steps 2 and 3 until you have fixed all the errors.
def another_function print("Syntax errors are annoying.") print("But at least python tells us about them!") print("So they are usually not too hard to fix.")
Solution
def another_function(): print("Syntax errors are annoying.") print("But at least python tells us about them!") print("So they are usually not too hard to fix.")
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 a function call are matched to parameters in function definition.
Functions may return a result to their caller using
return
.