Chapter 8

USER-DEFINED FUNCTIONS


Topics Covered:

  • Functions
  • Return values
  • Parameters
  • Arguments

Functions

Throughout the first seven chapters, we learned about many of Python’s built-in functions, including print, input, and round. Often, especially as our computer programs get longer and more complex, it is convenient to write our own functions. It is worth considering the reasons to create functions, which are sometimes called subroutines or subprograms.

Advantages of including user-defined functions in a project:

  • Code efficiency: Instead of duplicating a block of code, you can write a function that implements that block and calls it multiple times.
  • Simplify problem solving: You can take a complex problem and break it into smaller tasks, and then write a function for each of the tasks.
  • Code readability: It is easier to read a structured program consisting of multiple functions than a long listing of code containing no subroutines.
  • Reuse of code: Functions that perform a specific task can often by recycled or reused in multiple programs.
  • Ease of debugging: When troubleshooting and testing code, it is easier to focus on one subroutine at a time than to try to examine one big, long program.
  • Teamwork: Software developers frequently work in groups on large programming projects. Breaking the projects into subroutines naturally simplifies the distribution of the workload among team members.

To write your own Python function, you use the word def (short for define), followed by the FunctionName and a ParameterList enclosed in parenthesis, ending with a colon. Similar to an if statement or loop, the Action block of instructions included in the function must be indented at the same level. The final instruction in the function is an optional ReturnStatement.

def FunctionName (ParameterList):

   Action

   ReturnStatement

To get a better feel for how functions work, we will take a look at several examples. In the first example, we define a function called printFruit that will simply print “Apple”, “Banana”, and “Cherry”, each on a separate line. The printFruit function has no parameters and does not explicitly return a value. This definition creates the function, but we actually need to call it for the function to get triggered and run. To call the function, we provide the function name followed by parentheses. In the example below, we make three calls to the printFruit function.

# Define a function to print some fruit

def printFruit():

   print(“Apple”)

   print(“Banana”)

   print(“Cherry”)

# Make 3 calls to the printFruit function

printFruit()

printFruit()

printFruit()

The output from running the above program is displayed here:

Some functions, such as printFruit, perform a task, but don’t return an explicit value. Other functions computer a result (and may also perform a task) and return that single result to the user. A Python function can actually return multiple values.

In our next example, we will write a function that converts a Fahrenheit temperature to its Celsius equivalent. You can think of a function as a mini program. The inputs to the function are its parameters. A parameter is simply a placeholder variable that is listed in parenthesis in the heading of the function definition. The output of the function is produced using a return value, which is a data item that is sent back to the function call.

In the convertToCelsius function, a parameter named fahren is passed to the function. The formula (5/9)*(fahren-32) is applied to that parameter and the result is stored in a variable named cels. This cels variable is then returned by the function.

After the function definition, the program illustrates three different ways you might make a call to convertToCelsius. Since the function has a parameter, the function call must send an argument to the function. An argument is the actual value passed to the function within parentheses when the function is called. (Note: Sometimes the parameter shown in the function definition is referred to as the formal parameter and the argument that is supplied when the function is invoked is referred to as the actual parameter.)

In the first function call, we actually hard-coded the number 65 as the function argument and included the function call within a print statement. The value that returned the function, 18.333, was displayed. In the second function call, we passed 90 as the function argument, but this time we stored the return from the function, 32.222, to the variable amount. In the third example, we used keyboard input from the variable fahrenheit as the argument to the function. With a user input of 28.3, the result, -2.055, was returned to a variable named celsius.

The output when running the above program with the user entering 28.3 at the keyboard when prompted:

Modeling a Function using a Flowchart

When using flowcharts to design or document a program, you should create one flowchart for each of the program’s functions and another flowchart for the main program. Later, we will show how you can actually put the main body of the program in its own function. A new rectangular symbol, labeled as “process” by the draw.io website, is used to model a function call.

You should include the function name, parameters, as well as a stored variable where appropriate in this shape. In the actual function flowchart, the initial ellipse should include the function name (with parameters) instead of the label “start.” The final ellipse should include the return statement instead of the label “end.” The flowchart below models the convertToCelsius program, although only the third example is illustrated:

The following example uses a function pay to compute the weekly payroll. The hourly wage and the total hours are input to the function as parameters. The pay amount is computed, providing overtime pay for hours worked over 40. Once computed, that amount is returned.

The program asks the user to input empWage and empHours at the keyboard. These values are passed to the function as arguments. The amount returned is store to the variable empPay and then printed. The complete program and a sample run are shown next:

Here is the interaction that takes place when the program is run, and the user enters 9.35 as the hourly wage, and 27 as the weekly hours worked.

INTERACTIVE – Function fun!

The program below illustrates several simple functions and calls made to them. Try to predict the output of the program and then run it to see if you nailed it!

The scope of a variable is the section of the program where that variable is visible. A variable that is first initialized in a block is said to be local to that block. It is not visible, or available, outside of the block. A variable that is accessible in the entire file is said to have global scope. The global keyword can be used to declare a variable as global, even if this declaration is made inside of a block. The following code illustrates several examples of scope:

Chapter Review Exercises:

8.1. Name six advantages of creating user-defined functions.

Programming Projects:

8.1. Modify Programming Project 6.2 in the following ways:

  • Write a copyCost function that will have one argument, the number of copies. It should compute the cost based on the given formula and then return that cost.
  • Write a main function that will ask for the customer’s name and the number of copies. It will then make a call to your copyCost function and store the result to a variable. Finally, it should print the customer’s name and the copy cost (using a dollar sign and 2 decimal places).
  • Create a flowchart to model your solution.