Writing Functions

Overview

Teaching: 10 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!

Arguments in call are matched to parameters in 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 return a result to their caller using return.

Definition and Use

What does the following program print? Edwidge Danticat gave a lecture yesterday here.

def report(author):
    return 'author was' + author

report('Edwidge Danticat')

Solution

author is Edwidge Danticat

Calling by Name

What does this short program print?

def add_https(url):
    joined = "https:" + url
    return joined

my_url = "//www.loc.gov/item/2006627699/"
correct_url = add_https(my_url)
print(correct_url)

Using the .format() method on strings

We’ve been using the + to add strings together. We can also use format to create strings.

genre = "Fiction"
subject = "Haitian Americans--{}".format(genre)
print(subject)

[SLIDE]

Rewrite the add_https() function to use .format() instead of concatenating strings.

** Answer **

def add_https(url):
    joined = "https:{}".format(url)
    return joined

my_url = "//www.loc.gov/item/2006627699/"
correct_url = add_https(my_url)
print(correct_url)

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.