Functions – Writing and Using Functions

In this post, we discuss function definitions and function calls in Python. We explain how functions can be written and how, once a function is written, it must be called. We include several examples of functions.  The post includes three videos summarizing the material on functions: one  how to write a function, one how to call a function, and one presenting  examples of calling a function incorrectly.

A function definition starts with the phrase “def”, followed by the name of the function, a list of arguments (which could be empty), and a colon.  The statements forming the body of the function are indented.

Python allows you to place a function anywhere in the program, as long as the function is defined before it is used. However, it is a good idea to not scatter functions throughout the program, but to place them where they logically belong and make the program easy to read.  This often means functions are defined at the beginning of the file. More experienced programmers put functions into separate files and import them as needed.

The three functions we introduced in Functions – Basics: printGreeting, printPersonalizedGreeting, and calculateTax. To improve readability, encourage your students to start the name of a function with a verb describing the action of the function and to give a meaningful overall name (make multiple-word names readable by using caps or underscores). Avoid names that are reserved words in the language (e.g., print, max, append) and avoid short names with no relationship to the function (e.g., f1, xx, n).

All three of the functions have comment lines above the def statement. Encourage your students to provide a description of the function in the form of a comment above each function definition. This should include a brief description on what is done, what the arguments are, what is returned and, if appropriate, what is printed and what other I/O is performed. NOTE: When introduced to functions, many students struggle with the difference between output and return values. It is a good idea to discourage them from including print statements inside functions.

After a function has been defined, it can be called (or invoked), as often as needed. Function printGreeting is called using printGreeting() (i.e., the parenthesis are needed). Let’s take a look at function printPersonalizedGreeting:

def printPersonalizedGreeting(name):
    print "Good Morning,", name

The function needs to be called with one argument which is printed. Here are some examples on how to call the function:

printPersonalizedGreeting("John")
Good Morning, John

myName = "Jane"
printPersonalizedGreeting(myName)
Good Morning, Jane

What happens when the argument in the call to printPersonalizedGreeting is an integer, say variable x with value 10? The function will print the argument given and thus print

Good Morning, 10

Before we start a detailed example, we review Python’s basic rules and conventions about parameters and arguments.

  • Most functions have parameters (also called formal parameters).
  • Stress to your students to check that in any function call the parameters listed in the definition of the function and the arguments used in the call “match up”. This means they have the same number and types match.  Python allows flexibility on matching parameters and arguments; for example, the range function can have one to three arguments. A full discussion of this goes beyond the introduction to functions.
  • In Python, arguments are passed by value except for mutable objects like lists. This will be discussed and illustrated in our examples and videos, as well as in this Misconceptions and Challenges post about the difficulty of understanding how parameters are passed.
  • Most functions have a return statement. Functions operating on lists may not have one as lists are not passed by value. Our examples will discuss various scenarios.
  • Variables defined in a function are called local variables and exist only while the function is executed. Variables defined outside a function are called global variables.
## function calculateTax has two arguments
## It assumes implicitly that the second argument (rate) is between 0 and 100
## After excluding the first $100 of amount, the tax is computed using
## rate and returned.
##
def calculateTax(amount, rate):
    if amount <= 100:
        tax = 0
    else:
        tax = (amount-100) * rate / 100
    return tax

The value returned can be assigned to a variable, used in an expression or printed. Here are correct function calls:

print(calculateTax(500, 2))
tax = calculateTax(10000, 25)

earnings = 50000
mytax = calculateTax(10000, 7) + calculateTax(earnings, 20)

The following videos address many of the rules and conventions using function calculateTax as an example. The videos address:

  • calculateTax(2, 500): Interchanging the two arguments creates no error, but most likely will produce the wrong results
  • calculateTax( ), calculateTax(100), calculateTax(500, 2, 20): no, one or more than two arguments results in an error
  • after the call to function calculateTax, local variables amount, rate, and tax are undefined (unless they exist outside the function; see discussion on global variables for more detail)
  • calculateTax = calculateTax(10000, 25): does not create an error, but it is likely to have unintended consequences. The statement creates a variable calculateTax.  Once this variable exists, function calculateTax no longer exists!
  • Discussed further in the FunctionsMaterialForTeachers documents: the statement calculateTax returns <function calculateTax at 0x01C63EB0> (or something similar).

calculateTax Part I – How to write a function Video Length: 5:30


calculateTax Part II – How to call a function Video Length: 5:59

calculateTax Part III – Incorrect calls of a function Video Length: 8:49