Functions II

Break programs down into functions to make them easier to understand.

  • Human beings can only keep a few items in working memory at a time.

  • Understand larger/more complicated ideas by understanding and combining pieces.

    • Components in a machine.

    • Lemmas when proving theorems.

  • Functions serve the same purpose in programs.

    • Encapsulate complexity so that we can treat it as a single “thing”.

  • Also enables re-use.

    • Write one time, use many times.

Define a function using def with a name, parameters, and a block of code.

  • Begin the definition of a new function with def.

  • Followed by the name of the function.

    • Must obey the same rules as variable names.

  • Then parameters in parentheses.

    • Empty parentheses if the function doesn’t take any inputs.

    • We will discuss this in detail in a moment.

  • Then a colon.

  • Then an indented block of code.

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

Defining a function does not run it.

  • Defining a function does not run it.

    • Like assigning a value to a variable.

  • Must call the function to execute the code it contains.

print_greeting()

Arguments in call are matched to parameters in definition.

  • Functions are most useful when they can operate on different data.

  • Specify parameters when defining a function.

    • These become variables when the function is executed.

    • Are assigned the arguments in the call (i.e., the values passed to the function).

    • If you don’t name the arguments when using them in the call, the arguments will be matched to parameters in the order the parameters are defined in the function.

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

print_date(1871, 3, 19)

Or, we can name the arguments when we call the function, which allows us to specify them in any order:

print_date(month=3, day=19, year=1871)

Or, we can name the arguments when we call the function, which allows us to specify them in any order:

print_date(month=3, day=19, year=1871)

Functions may return a result to their caller using return.

  • Use return ... to give a value back to the caller.

  • May occur anywhere in the function.

  • But functions are easier to understand if return occurs:

    • At the start to handle special cases.

    • At the very end, with a final result.

def average(values):
    if len(values) == 0:
        return None
    return sum(values) / len(values)

a = average([1, 3, 4])
print('average of actual values:', a)
print('average of empty list:', average([]))
  • Remember: every function returns something

  • A function that doesn’t explicitly return a value automatically returns None.

def returnNone(x):
    print('Doesnt have return, but returns None')

value = returnNone(10)
print(value)