UW AMath High Performance Scientific Computing
 
AMath 483/583 Class Notes
 
Spring Quarter, 2011

Table Of Contents

Previous topic

Numerics in Python

Next topic

Python Namespaces

This Page

Python functions

Functions are easily defined in Python using def, for example:

>>> def myfcn(x):
...     import numpy as np
...     y = np.cos(x) * np.exp(x)
...     return y
...

>>> myfcn(0.)
1.0

>>> myfcn(1.)
1.4686939399158851

As elsewhere in Python, there is no begin-end notation except the indentation. If you are defining a function at the command line as above, you need to input a blank line to indicate that you are done typing in the function.

Defining functions in modules

Except for very simple functions, you do not want to type it in at the command line in Python. Normally you want to create a text file containing your function and import the resulting module into your interactive session.

If you have a file named myfile.py for example that contains:

def myfcn(x):
    import numpy as np
    y = np.cos(x) * np.exp(x)
    return y

and this file is in your Python search path (see Python search path), then you can do:

>>> from myfile import myfcn
>>> myfcn(0.)
1.0
>>> myfcn(1.)
1.4686939399158851

In Python a function is an object that can be manipulated like any other object.

Lambda functions

Further reading