Link Search Menu Expand Document

User-defined Functions

Table of contents

  1. Description
  2. Composition
  3. Example
  4. Passing Arguments
    1. Functions as “Black Boxes”

Description

User-defined functions are custom functions defined by a programmer. They are used to organize code and reduce repetitive code. After a function is defined, they can be executed by calling their name. Functions are not executed when they are defined.

Composition

def function_name(parameter1, parameter2):
    # function code indented under definition
    # more function code
    # even more function code

function_name(argument1, argument2)

Example

The example program below accepts the user’s height and weight, calculates the BMI, then displays the result to the console. Step through the program and observe what is happening in memory to better understand how user-defined functions work.

The program consists of 3 seperate functions (main, calculate_bmi, calculate_inches). These three functions organize the code and make the main algorithm more readable. There are no commands or variables occupying the global space, all code is inside functions (this is always best practice when programming).

As you step through the execution of the program, notice that some functions have return values, some do not. Also notice that some functions accept arguments, but some don’t. It all depends on how the programmer defines the function.

  • Note: Parameter names in the function definition do not need to match argument names in the calling statement. Quantity must match, though.

Also notice that functions are only executed when they are called by their name, not when they are initially defined.

Passing Arguments

When arguments passed to a function are immutable (strings, integers, etc), a copy of the value of the argument is assigned to the function parameter. When the data type of an argument passed to a function parameter is mutable, a reference to the actual argument is passed. This can cause unwanted side effects.

Functions as “Black Boxes”