Overview

Teaching: 15 min
Exercises: 15 min
Questions
  • 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.

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.

def print_greeting():
    print('Hello!')

Defining a function does not run it.

print_greeting()
Hello!

The arguments in a function call are matched to the parameters in function definition.

def print_date(year, month, day):
    joined = str(year) + '/' + str(month) + '/' + str(day)
    print(joined)

print_date(1871, 3, 19)
1871/3/19

Functions may send back a result using the return statement.

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

Remember that every function returns something, even if ‘something’ equals 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)
  1. Why do you think it’s okay to call the arguments in a different order like this?
  2. 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

  1. Read the code below and try to identify what the errors are without running it.
  2. Run the code and read the error message. Is it a SyntaxError or an IndentationError?
  3. Fix the error.
  4. 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