# Python Function FAQ

Barry Tolnas
The Evergreen State College
tolnasb@evergreen.edu

The concept known as "functional abstraction" is a cornerstone of computer science. A thorough understanding of how to read, write, and use functions properly is a prerequisite both for writing good software and for understanding concepts in computer science.

# What is a function?

A function is a set of instructions grouped together which altogether perform some useful task—particularly a task that will need to be done in several different places in a program. For example programs that need to do some geometry such as our physics programs often need to compute the sine of various angles. Python provides a function called `sin()` for this purpose. The sequence of instructions which performs the sine function accurately on a typical computer is surprisingly long and complicated. Rather than cutting and pasting the instructions to compute sine wherever you need to compute the sine of an angle, you can simply use the `sin()` function.

# How do I use a function in Python?

When you want to use a function to perform a task in a Python program you put a "function call" into your program. A function call looks like this in Python:
```a = sin(pi)
```
This call to the `sin()` function executes all of the instructions needed to compute the sine of π and assigns that value to the variable `a`. The `pi` in the parentheses is called the argument to the function. The value it computes is called its "return value". You can imagine that the computer substitutes the return value in place of the function call so in this example `sin(pi)` gets replaced with '0' so the statement becomes ```a = 0```. Similarly, the statement `print sin(pi)` would just print out '0'.

Functions may have several arguments separated by commas:

```answer = ultimate_answer( life, universe, everything )
print answer
```

It is also possible to have a function that has no arguments if that function needs no information to perform its task. However when you call any function you must always supply the parentheses for python to recognize you are trying to call a function:

```weather = random()
```
As described above, Python functions may also return more than one thing at a time. The following function returns two values which are assigned to 'x' and 'y' respectively:
```x,y = displacement(t,x0,v,a)
```

# What can functions do?

In mathematics, a function is a computation that evaluates to a single numerical value which usually depends on the value of one or more numerical arguments. In Python, a function is not restricted to returning a numerical value. A Python function returns a Python "object" which can be a number, a string of characters, or more complex objects. Python functions may return more than one value or nothing at all. In computer science, functions which don't return anything are known as "procedures".

# What good is a function that returns nothing?

Well it wouldn't be good for anything at all except that functions can have "side effects". You could call a function which prints out something on the screen but doesn't return a value. Printing a message was a useful side effect. Other side effects might include displaying graphics, opening and closing files, or modifying the values of the function's arguments.

# Why use functions?

1. Save work - A described above when you use a function in your code, you are effectively replacing a sequence of instruction which may be very long with a function call.
2. Make programs easier to read and understand - If I'm trying to take the sine of an angle it seems much more clear to anyone reading the program to call `sin(angle)` than to have all of the complex code to do it copied everywhere in my program I need it. Imagine if every time a recipe called for stirring the ingredients it said, "pick up spoon, lower spoon into bowl, move spoon in circular motion, repeat, repeat..."
3. Simplify program maintenance - If I change the definition of a function then the change works everywhere that function is called in my program. I don't need to go change every place where I performed a certain task when I discover a better way to do it.
4. Increase efficiency - If only one copy of a sequence of instructions exists, then less space is needed to store the program either on a disk drive or in memory. Every time that task is needed, a program jumps to the same sequence of instructions

# What is a "library" in computerspeak?

Groups of related functions which are usually expected to be used together are called a "library". For example the `math` library includes the most commonly used math functions to compute things like sine, cosine, and square root. The corresponding math library functions are `sin()`, `cos()`, and `sqrt()` respectively. Libraries are typically designed for use by programs written in particular languages. Libraries written for use with Python are called "modules" which exist on your hard disk in various forms. They may be Python programs you can read, or they may be "compiled" into an "executable" format that can only be read by the computer but which runs much faster. On Windows these appear as ".dll" files.

# When I try to use a function in my program, the Python interpreter gives me a message like "NameError: name 'sin' is not defined". What going on here?

Before you can use a function in your program you must tell the Python interpreter where to find the code which must be executed when you call that function. This code is in a module as described above. You tell Python you want to use the functions in a library by "importing" its module like this:

```from math import *
```
This statement says, "import all of the functions in the `math` library. If you only want to use one or two functions out of a library, you can say that like this:
```from math import sin, cos, tan
```

# How does Python know where on my disk drive to find library modules? or How do I get rid of this error message: "ImportError: No module named...."?

If you get that error, first make sure you spelled the module name right! Python searches for modules in a predefined list of directories for a file matching the name of the module being imported but with a '.py' or '.pyc' extension. First it looks in the current directory, then in the list of directories in an environment variable called PYTHONPATH. The method to examine and modify environment variables varies from one operating system to another and is beyond the scope of this FAQ. There is an explanation in the Modules chapter of the Python Tutorial.

# How do I find out all of the functions available?

The first place to explore is the Python Library  Reference which documents the functions included with a standard distribution of Python. One special group of functions are the "builtin" functions which are always available without being imported. Global Modules Index.

# What if I want to use function from a library that was created for some other computer language?

It is possible to use libraries that were not written for Python by creating what are known as "wrappers" around the functions which make functions designed for other languages, most commonly C. Because there are automated software tools which ease the effort required to creating these wrappers, most useful libraries already have a wrapper created for them so they are accessible to Python. These wrappers must be downloaded and installed separately to extend Python.

A popular tool for creating wrappers for use by various languages including Python is called SWIG, the "simplified wrapper and interface generator".