Python functions - some examples

This notebook demonstrates how to work with python functions, including some complex examples.

Some useful links:

A very simple function

This function takes no parameters and doesn't explicitly return a value. Note that a function with no return actually returns "None".


In [ ]:
def print_hello():
    print("hello!")

# call the function and store its output.  You don't really have to have the output= part if you don't want to.
output=print_hello()

print("output of print_hello() is:", output)

A function with one argument and one returned quantity

This function takes in one parameter, thisval, and returns the square of it. We'll store the output in a variable and print it.


In [ ]:
def squareme(thisval):
    return thisval**2

output = squareme(4)

print("output of squareme() is:", output)

A function with several arguments and one returned quantity

This function takes three arguments and returns their sum.


In [ ]:
def sum_me(a,b,c):
    sum = a+b+c
    return sum

output = sum_me(1,2,3)

print("output of sum_me() is:", output)

A function that returns multiple quantities

Python allows functions to return multiple quantities. The quantities returned can be of any type: numbers, strings, lists, arrays, and so on. You can either put all of the returns into a single variable (and can then extract the various returns through indexes) or put the returned quantities into one variable per returned quantity.

Note: For the purposes of the function below, we're assuming that the input values a, b, and c are all integers - however, think about what might happen if they were some combination of numbers and other quantities (such as strings or lists). What do you think the function would do?


In [ ]:
def more_math(a,b,c):
    d = a+b+c  # should be a number
    e = [a,b,c]  # should be a list of three numbers
    f = str(a) + str(b) + str(c)  # should be a string composed of three characters, each of which is a number
    return d,e,f

In [ ]:
# put all returns in one variable
val1 = more_math(2,4,6)

print("printing out all returns in one variable:", val1)
print("")  # adds an extra line
print("getting the second returned quantity:",val1[1])
print("")
print("second quantity is a list.  Getting one value out of that list:",val1[1][2])

In [ ]:
# put returns in separate variables
val2, val3, val4 = more_math(8,10,12)

print("first return:", val2)
print("second return:", val3)
print("third return:", val4)

What do you think happens if you have more than one variable, but not the right number of variables to accept all of the returns?


In [ ]:
val5, val6 = more_math(14,16,18)

A function that has default arguments

Python allows you to have functions that have a default value for one or more arguments. This allows you to call a function with fewer arguments than it is defined to allow (i.e., fewer than the maximum number of possible arguments). In function definitions of this sort, the mandatory arguments (ones that do not have a default value) must come before the optional arguments (ones that have default values). This can be extremely helpful in many circumstances, and can be called in several ways:

  1. Giving only the mandatory argument
  2. Giving the mandatory argument plus one of the optional arguments
  3. Giving the mandatory argument plus two or more of the optional arguments

There does not need to be a mandatory argument - all arguments can have defaults! Note that if you are going to give more than just the mandatory argument, the optional arguments need to be given in the order they are defined. In other words, you can't just give the mandatory argument and the second optional argument in a function with one mandatory argument and multiple optional arguments - you have to give all arguments up to the one that you want.


In [ ]:
# this version has one default value

def print_stuff(first,second='dog',third='monkey'):
    print(first,second,third)

In [ ]:
print_stuff('cat')

In [ ]:
print_stuff('cat','elephant')

In [ ]:
print_stuff('donkey','wolf','mouse')

In [ ]:
# this version has no default values!

def print_stuff_2(first='fish',second='bird',third='dinosaur'):
    print(first,second,third)

In [ ]:
print_stuff_2()

In [ ]:
print_stuff_2('newt')

In [ ]:
print_stuff_2('vole','koala')

In [ ]:
print_stuff_2('lion','armadillo','cow')

A function that has keyword arguments

Finally, functions can also be called with "keyword arguments" that have the form keyword=value. For example, the function below has one mandatory argument and two keyword arguments. The mandatory arguments must always be called first, and in the same order that they appear in the function call. The keyword arguments have to be after that, and can be called in any order. Note that you don't have to take advantage of the keywords - it's perfectly acceptable to just treat the keyword arguments as arguments with default values (because that's actually what they are!) and just give them in the order they appear in the function call. For example:


In [ ]:
# function with one mandatory argument, two keyword arguments
def orbit(mass1, mass2=1.0, distance=17.0):
    print("mass1:   ", mass1)
    print("mass2:   ", mass2)
    print("distance:", distance)

In [ ]:
# just the mandatory argument
orbit(3.0)

In [ ]:
# two arguments, given in the order they appear in the function call.
orbit(3.0,9.0)

In [ ]:
# the mandatory argument and one keyword argument
orbit(3.0,distance=8.0)

In [ ]:
# the mandatory argument and the two keyword arguments given out of order
orbit(5.0,distance=3.0,mass2=17.0)

A note about functions with keyword arguments

A function with keyword arguments does not need to have any default arguments at all. For example:


In [ ]:
# function with all keyword arguments
def orbit_new(mass1=3.0, mass2=1.0, distance=17.0):
    print("mass1:   ", mass1)
    print("mass2:   ", mass2)
    print("distance:", distance)

In [ ]:
orbit_new()

In [ ]:
orbit_new(distance=9.0)

In [ ]:
orbit_new(distance=5.0,mass1=81.0)

In [ ]:
orbit_new(distance=5.0,mass2=0.7,mass1=81.0)