Packages, functions, and modules

An important part of coding (in Python and in other modern language) is organizing code in easily re-used chunks.

Python can work within both a procedural and an object-oriented style.

Procedural programming uses functions

Object oriented uses classes. Today we'll discuss procedural, next week we'll discuss object oriented programming.

What is a function?


In [7]:
def fizzbuzz(ntot, show=True):
    pass

You can name your function anything, as long as it doesn't start with a number, isn't a built-in keyword, and only contains numbers, letters, and underscores

Note for IDL users: there is no difference between functions and procedures. All Python functions return a value: if no return is specified, it returns None


In [10]:
def addnums(x, y=3):
    return x + y

In [11]:
addnums(2, 4)


Out[11]:
6

In [13]:
addnums(5)


Out[13]:
8

In [14]:
addnums("A", "B")


Out[14]:
'AB'

Python functions use local variables, unless you use the global variable definition

Documentation rocks, too!


In [15]:
def power_of_difference(x, y, p=2.0):
    """Return the power of the difference of x and y
    
    Parameters
    ----------
    x, y : float
        the values to be differenced
    p : float (optional)
        the exponent (default = 2.0)
    
    Returns
    -------
    result: float
        (x - y) ** p
    """
    diff = x - y
    return diff ** p

power_of_difference(10.0, 5.0)


Out[15]:
25.0

In [16]:
help(power_of_difference)


Help on function power_of_difference in module __main__:

power_of_difference(x, y, p=2.0)
    Return the power of the difference of x and y
    
    Parameters
    ----------
    x, y : float
        the values to be differenced
    p : float (optional)
        the exponent (default = 2.0)
    
    Returns
    -------
    result: float
        (x - y) ** p


In [17]:
import mymodule

In [18]:
import mymodule as m

In [19]:
from mymodule import *

In [20]:
from mymodule import add_numbers

Common modules that are useful! numpy, scipy, matplotlib, astropy, pyfits, pandas, scikit-learn

Plotting freestyle time. We'll discuss numpy arrays, and then plot up a vs e from the asteroids table, and talk about some of the basics and import things in numpy and scipy.

Making nice looking code: "code is read much more often than it is written"

The official rules are PEP-0008: https://www.python.org/dev/peps/pep-0008. This is the "The Elements of Style" for Python!

You should read this. In general, white space is a good thing, lines should have a finite width (79 characters), and comments are good to have! You'll often find yourself needing code that you wrote >2 years ago, and it's a bad thing if it takes you longer to understand the code than it would to re-write it from scratch!


In [ ]: