Table Of Contents

Previous topic

Control Flow Statements

Next topic

Modules

This Page

Download this page as:

Writing Functions

Basic syntax

As with other languages, you can write functions in Python to avoid repeating code and to improve flow of your programs. Functions use a similar indented syntax to the loops introduced earlier, with a colon after the function name and the following lines indented. As with loops, it is considered good python style to indent with four blank space. Let’s start by defining a simple function:

In [1]: def my_function():
   ...:     print("Hello World!")
   ...: 

This can be called with my_function():

In [2]: my_function()
Hello World!

Note

It is considered good python style to have function names all in lower case, with words separated by underscore if it improves readability.

This is a rather boring function that does not take nor return any arguments. Let’s make things a little more complicated:

In [3]: def add_two_numbers(x1, x2):
   ...:     total = x1 + x2
   ...:     return total
   ...: 

In [4]: y = add_two_numbers(3,5)

In [5]: print(y)
8

This function simply adds the two numbers that it is given as arguments. As you expect, we can pass integers, floats and strings to a function. Actually, we can pass any Python object, even functions! You can also return any number of arguments.

Positional and keyword arguments

Consider the following function:

In [6]: def print_argument(x=5):
   ...:     print(x)
   ...: 

In this example, we have defined what the default value of the x variable in the function. This is called a keyword argument, as opposed to a positional argument. If you try and call this function without any arguments, the default will be used. If you call it with an argument, the specified value will be used:

In [7]: print_argument()
5

In [8]: print_argument(3.)
3.0

In [9]: print_argument(x=3.)
3.0

Exercise

Write a function that prints the value of input argument multiplied by 7. If no argument is given, it should print 7. If the input argument is 6, it should print “The Answer to the Ultimate Question of Life, The Universe, and Everything.”

Click to Show/Hide Solution

In [10]: def multiply_by_7(x=1):
   ....:     if x == 6:
   ....:         print("The Answer to the Ultimate Question of Life, "
   ....:               "the Universe and Everything.")
   ....:     else:
   ....:         print(x*7)
   ....: 

In [11]: multiply_by_7()
7

In [12]: multiply_by_7(4)
28

In [13]: multiply_by_7(6)
The Answer to the Ultimate Question of Life, the Universe and Everything.

Functions can have both positional and keyword and arguments. The former are required (i.e. not giving them will result in a TypeError), the latter are optional:

In [14]: def slicer(seq, start=None, stop=None, step=None):
   ....:     """ Implement basic Python slicing."""
   ....:     return seq[start:stop:step]
   ....: 

In [15]: l = [1, 2, 3, 4, 5, 6]

In [16]: slicer()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/naw/VM-Share/GREAT-ITN/GITN-Meetings/GITN-School-Alicante-Jun13/degroote-doc-v2/<ipython-input-16-3c8febe6fdb8> in <module>()
----> 1 slicer()

TypeError: slicer() takes at least 1 argument (0 given)

In [17]: slicer(l)
Out[17]: [1, 2, 3, 4, 5, 6]

In [18]: slicer(l, stop=2)
Out[18]: [1, 2]

In [19]: slicer(l, stop=5, step=2)
Out[19]: [1, 3, 5]

Docstrings

You can use a single string after the first line of a function to describe what the function does and what its parameters are. The general convention is:

In [20]: def funcname(params):
   ....:     """Concise one-line sentence describing the function.
   ....: 
   ....:     Extended summary which can contain multiple paragraphs.
   ....:     """
   ....:     # function body
   ....:     pass
   ....: 

Then the docstring for that function can be accessed with:

In [21]: help(funcname)
Help on function funcname in module __main__:

funcname(params)
    Concise one-line sentence describing the function.
    Extended summary which can contain multiple paragraphs.

In IPython you can access the same documentation using funcname? (Try it now!).

Copyright: Smithsonian Astrophysical Observatory under terms of CC Attribution 3.0 Creative Commons
 License