Creating your own functions

Updated on 28 Dec 2022

Whether you know it or not, we’ve already been using functions. len() is a function, and str.split() is a class method (another name for a function inside in class). In this section we’ll look at creating our own functions.

basic function

We’ve done a fair bit of coding so far, and what I would like to see is a function that can return a random quote. Let’s see how we might do that.

import random

def random_quote():
    quotes = [
        'git',
        'imbecile',
        'invented TIM',
        'need to ask yourself, what are we really trying to solve'
    ]

    return random.choice(quotes)

print(random_quote())

The synopsis for a function is:

def function_name():

The code within the function is indented; just like you would in loops and conditionals. The function also has the option of returning data; just as we have with our random_quote function.

parameters

It is also possible to pass parameters to your function. These paramaters can then be used inside your function code. Let’s create a function that accepts a parameter.

def merge_letter(firstName):
    myStr = 'Dear ' + firstName + ', you are welcome'

    return myStr

full_letter = merge_letter('brent')
print(full_letter)

additional

We can keep adding more parameters if we want, including default values. In the example below, we must supply values for firstName and lastName, however title is optional. If no value is supplied for title, it will default to an empty string.

def merge_letter(firstName, lastName, title=''):

named parameters

Python supports positional and named notation when it comes to calling functions. So far we’ve used positional notation.

  • Positional Notation: We supply the parameters in the exact order that they are required by the function definition.
  • Named Notation: This means that we supply the name of the parameter with the value.

Example of named notation

def merge_letter(firstName, lastName, title=""):
    ...

# call merge_letter function with named parameters
merge_letter(firstName = 'brent', lastName = 'knigge')

In the example above, it doesn’t matter what order we put the parameters in because they are named!

Dynamic parameters

There could be cases where we want to call a function with an unknown number of parameters. This might occur where we are reading the columns headers of an Excel spreadsheet. There might be 4 columns, but then again there might be 10 columns. How do we create a function that can handle this case?

args

One technique is with args. In the example shown below, we simply define a args parameter which we can loop over displaying the values of what was passed to the function.

def do_columns(*args):
    for arg in args:
        print(arg, end=' ')

    lenStr = str(len(args))
    print('there are ' + lenStr + ' parameters passed')

do_columns('hi', 'ho', 'yi', 'yo')

keywords

The technique above was really good in passing a dynamic number of parameters. Unfortunately we only got values and not the name of the parameter that it is related to. What is hi, what is ho? Do we need to know the parameter name?

Let’s look at a different example. In the example below I am passing first_name and last_name, but how does my function know that?

do_columns('brent', 'knigge')

I could assume that the arguments will be in order of first_name, last_name, but what about the remaining data? Or data that is missing? It might be better to have something like this instead.

do_columns(first_name = 'brent', last_name = 'knigge', admin = True)

Now we just have to write our function definition to accept dynamic parameters with the paramater name.

def do_columns(**keywords):
    
    for kw in keywords:
        print(kw, ': ', keywords[kw])

    lenStr = str(len(keywords))
    print('there are ' + lenStr + ' parameters passed')
    
do_columns(first_name = 'brent', last_name = 'knigge', admin = True)

functions - guided exercise

We can call functions from other functions. Lets use the merge_letter and random_quote functions together. Using these functions, we want something similar to what is shown below.

Dear Brent, you invented TIM

solution

First off, lets put in the code that we need to start with. The function definitions (this is almost exactly the same code as function2.py).

import random

def random_quote():
    quotes = [
        'git',
        'imbecile',
        'invented TIM',
        'need to ask yourself, what are we really trying to solve'
    ]

    return random.choice(quotes)

def merge_letter(firstName):
    myStr = 'Dear ' + firstName + ', you are welcome'

    return myStr

Next we want to modify merge_letter so that it calls random_quote and builds the myStr variable.

.
.
.
def merge_letter(firstName):
    myStr = 'Dear ' + firstName + ', you ' + random_quote() 

    return myStr

print(merge_letter('brent'))

functions - extended exercise

Experiment with functions and find out what works and what doesn’t.

  • can I pass integers or lists as parameters?
  • can I pass a list to a function with dynamic parameters?