Python for Business Analytics

Writing functions


In programming, a function is a named sequence of statements that performs a desired computation. You can write a function by defining it in the Python language, which involves giving it a name and specifying the computations. Later, you call the function by its name.

The ability to write functions is perhaps one the elements of more active programming, as opposed to just using Python. There are several reasons to write functions:

  • Productivity: functions eliminate repetitive code. If you are performing the same sequence of computations many times, it makes sense to write it only once if possible. Furthermore, if you later need to make changes you only need to do it once.
  • Problem solving: writing functions allows you to divide a complex program into small manageable parts. This also makes it easier to debug each of these parts.
  • Readability: by giving a descriptive name to a group of statements your code will be easier to read.
  • Portability: well-designed functions are useful for many different projects. Once you write and debug one, you can always re-use it.

On DataCamp, you learned about how to import packages and call functions from this packages. For example:

In [1]:
import math
x=math.sqrt(9)
print(x)
3.0
In [2]:
from math import sqrt
x=sqrt(9)
print(x)
3.0

Your first function that will print the current date on the screen. For this, we will need to import the time package so that we can use it inside the function:

In [3]:
import time

We write the function as follows. The empty parentheses after the function name indicate that it takes no inputs. Note that the second line in indented with a tab (or four space). This makes Python understand that the indented block of code is part of the function. Jupyter adds the indentation automatically.

In [4]:
def today():
    print('Today is ' + time.strftime("%d/%m/%Y"))

To call the function:

In [5]:
today()
Today is 18/08/2016

By defining the function and running the corresponding the cell, Python will load it in the the memory for repeatead use. The type function from the standard Python library allows us to verify the type of each object that we create or load in our session:

In [6]:
type(today)
Out[6]:
function

Functions can take one or multiple arguments:

In [7]:
def hello(name):
    print('Hello ' + name)
    
def sum_two_numbers(a,b):
    print('The sum is ' + str(a+b))

You should test these two functions in a new cell. It is also possible to specify default values for arguments, such that that they become optional.

In [8]:
def hello_default(name='nobody'):
    print('Hello ' + name)

hello_default('Marcel')
hello_default()
Hello Marcel
Hello nobody

The functions that we created so far are called void functions, because they do not return any results (unlike the square root function from before). To return a result we define a function as follows.

In [9]:
def get_today():
    return time.strftime("%d/%m/%Y")

date=get_today()
print(date)
18/08/2016

A function will stop executing as soon as it reaches a return statement, which does not need to be the last line in the function. A function can have multiple return statements, as the following example illustrates.

In [10]:
def is_positive(number):
    if number>0:
        return True
    else:
        return False

print(is_positive(1))
print(is_positive(-1))
True
False

The above function uses an if/else block, which is a very important programming concept that you will study in more detail in the next module.

Writing Functions: Practice

Exercise 1

Write a function name right_justify that takes a string named S as a parameter and prints the string with enough leading spaces so that the last letter of the string is column 70 of the display (Think Python 3-1). Use the hints below.

In [11]:
repetition=5*'a'
In [12]:
len(repetition)
Out[12]:
5

Exercise 2

Write a function distance that takes as an input four numbers $x_1$, $x_2$, $y_1$, $y_2$ and returns the number given by the formula


\begin{equation} d(x,y)=\sqrt{(x_1-y_1)^2+(x_2-y_2)^2} \end{equation}

For example, when $x_1=2$, $x_2=-1$, $y_1=-2$, and $y_2=2$ the result is $5$.

In [ ]:
 

Exercise 3

A function object is a value that you can assign to a variable or pass as an argument. For example, the do_twice function below is a function that takes a function object as an argument and calls it twice:

In [13]:
def do_twice(f):
    f()
    f()

Here is an example that uses do_twice to call a function named print_spam twice.

In [14]:
def print_spam():
    print('spam')
    
do_twice(print_spam)
spam
spam

(a) Type this example into a cell and test it.

(b) Modify do_twice such that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.

(c) Define the print_twice function as in the cell below.

(d) Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.

(e) Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statemens in the body of this function, not four.

(Think Python 3-2)

In [15]:
def print_twice(word):
    print(word)
    print(word)

Exercise 4 (Challenging)

Many mathematical functions that appear in statistics have a recursive structure. We can also define recursive functions in programming. Based only on what we have seen in this notebook, write a function to compute the factorial of an integer number:


\begin{equation} n!=n\times(n-1)\times(n-2)\times\ldots\times2\times1 \end{equation}
In [ ]: