Functions

Recall: We have already seen that a variable is a named memory location bound to some value.

The fact we have a name allows us to access such value later on, and having a name makes it easier to remember, as opposed to the physical address in memory.

The idea of binding a name to a memory location can be extended to functions as well. We can look at a function then as a name bound to some code in memory.

In other words, the value in this case is simply a block of code to be executed later, when we actually call or invoke the function.

Where do the functions come from?

Some function calls

We will start with calling some built-in functions. Calling a function invokes the code the function is bound to.

Arguments may be given to the function to alter its behavior.

All functions return a value. If not explicitly specified the return value is None.

Converting values

Python offers some useful functions for converting one value to another. You may know this as typecasting.

The Math module

Python provides the math module with all the expected mathematical functions you may have used or may need to use. To use any module you must first import it.

The import creates a module object which allows you to access all the defined module properties (variables, functions, etc)

Defining a function

You define a function with def, followed by the function name, a set of parentheses () and a colon :. If there are no parameters to the function, the parentheses are empty.

That makes up the function header. The body of the function is next and each statement must be indented (conventionally 4 spaces). Indentation is how Python determines the body.

# A function definition
def functionName(optional parameters):  # The function header
    functionBody                        # The body

A function definition creates yet another object; a function object of type function.

Function subtleties

Since the program is parsed starting at the top moving down, a function defintion has to be read first (function object created) before you can call it. Same rule as variables; must define first before you use them.

Parameterized functions

Positional argument passing

Arguments are either positional or keyword.

Positional arguments depend on the argument's position in the argument list and are always required.

Basically each argument is copied to its respective parameter, i.e. first arg to first param, and so on.

Take a look at the display() function. It takes three parameters: a, b, and c.

When calling the function it is given the three arguments: 1, 2, and 3, all integer literal values. Integer variables could also have been used.

Keyword argument passing

Arguments are passed by name, not position. Each argument is preceded by a keyword that helps in readability.

Mixing positional and keyword arguments

You may combine positional with keyword arguments, but care must be taken.

Rule is: keyword arguments must follow positional ones.

Default parameter values

A parameter may have a default value. If it does, then you can omit its argument when calling the function, thus making the argument optional.

Functions and scopes

Scope determines the visibility of a name, i.e. what code can access the name directly.

The scope of a function's parameters and local variables is the function itself.

A variable defined outside a function is accessible within the function, but for reading only.

A variable assigned to inside the function shadows a variable defined outside the function.

The global keyword can be used to allow a function to update a variable defined outside the function.

Pass by Value

Arguments are always passed by value to a function.

In Python everything is an object which means variables hold references to such objects in memory.

Note however, some types are immutable (can't be changed) and some mutable (can be changed).

This distinction means that despite the fact that the parameter holds the same reference as the argument, if the type is immutable, a copy of the value is made instead.

So, above a and p are of type int, a scalar type, and thus immutable. When the value of p is changed, a new memory location is created that holds the new value, leaving the argument a unaffected.

pass by value immutable

Note: A Python source file (.py) is referred to as a module. When you run the script, the name of the module is identified as __main__.

Mutable object types will be affected by functions as we will see below with a list (cover them later).

Keep in mind that what happens with such types is the reference itself cannot change (pass by value remember), but the actual instance or value being referenced can be changed.

pass by value mutable

Practice problems

Create a separate Python source file (.py) in VSC to complete each exercise.


p1: repeatFunction.py

A function can call another function as you well know or guessed. So, for this exercise define two functions:

displayMessage() - takes a string message to print out repeatMessage() - takes the message to display calls the displayMessage() twice, passing it the message.

Sample output:

Pizza!
Pizza!

p2: grid2.py

Define a function that displays the following grid:

+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +

Hint: to print more that one value on a line, you can print a comma-separated sequence of values:

print('+', '-')

By default, print() advances to the next line, but you can override that behavior and put a space at the end, like this:

>

print('+', end=' ')
print('-')

The output of these statements is: '+ -'.

A print statement with no argument ends the current line and goes to the next line.


p3: grid4.py

Expand the grid2.py program to draw a 4 x 4 grid.

+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
[Variables] [TOC] [Conditionals]