{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Lecture notes for Rock and Paleomagnetism, Spring Quarter, 2016, UC San Diego Lecture 2 \"Python Programming Bootcamp\". \n", "\n", "by Lisa Tauxe\n", " \n", " Class website: \n", "http://magician.ucsd.edu/~ltauxe/sio247" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variable Types" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "The time has come to talk about variable types. We’ve been very relaxed up to now, because we don’t have to declare them up front and we can often even change them from one type to another on the fly. But - variable types matter, so here goes. Python has integer, floating point, string and complex variable types. It is pretty clever about figuring out what is required. Here are some examples:" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [], "source": [ "number=1 # an integer \n", "Number=1.0 # a floating point \n", "NUMBER='1' # a string \n", "complx=1j # a complex number with imaginary part 1 \n", "Complx=np.complex(3,1) # the complex number 3+1i\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try doing math with these!" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "2.0\n", "11\n" ] } ], "source": [ "print number+number # [ an integer] \n", "print number+Number # a float\n", "print NUMBER+NUMBER #[a string] " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But what about this!" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": false }, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnumber\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0mNUMBER\u001b[0m \u001b[0;31m# [Gives you an angry error message]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ], "source": [ "number+NUMBER # [Gives you an angry error message]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lesson learned: you can’t add a number and a string. and string addition is different! But you really have to be careful with this. Floats and integers sometimes work differently, as illustrated by the division below. So, if you want a float, use a float.\n", "\n" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "0.333333333333\n", "0.333333333333\n" ] } ], "source": [ "print number / 3 # division with 2 integers\n", "print Number / 3 # division with 1 float, 1 integer --> result will be float\n", "print number / 3. # same as above. the 3 is a float because of the \".\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you're ever uncertain about what kind of variable you have, you can use the type() function to find out." ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] } ], "source": [ "print type(number)\n", "print type(Number)\n", "print type(NUMBER)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can convert from one type to another (if appropriate) with:\n", "\n", " int(Number); str(number); \n", " float(NUMBER); complex(real,imag) \n", " \n", "complex() converts the two parts to a complex number.\n", "There is another kind of variable called \"boolean\". These are: true, false. There are special boolean operators: and, or, and not. For the record, the integer '1' is true and ‘0’ is false. These can be used to control the flow of the program as we shall learn later.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data structures" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In previous programming experience, you may have encountered arrays, which are a nice way to group a sequence of numbers that belong together. In Python we also have arrays, but we also have more flexible data structures, like lists, tuples, and dictionaries, that group arbitrary variables together, like strings and integers and floats - whatever you want really. We’ll go through some attributes of the various data structures, starting with lists." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Lists are denoted with square brackets, [ ], and can contain any arbitrary set of items, including other lists!\n", "* Items in the list are referred to by an index number, starting with 0.\n", "* You can count from the end to the beginning by starting with -1 (the last item in the list), -2 (second to last), etc.\n", "* Items can be sorted, deleted, inserted, sliced, counted, concatenated, replaced, added on, etc.\n", "\n", "Here are a few examples of things you can do with lists:\n" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 2.0, '400', 'spam', 42, [24, 2]]\n", "400\n", "[24, 2]\n", "['a', 26.3, '400', 'spam', 42, [24, 2]]\n", "['a', 26.3, '400', 42, [24, 2]]\n" ] } ], "source": [ "mylist=['a',2.0,'400','spam',42,[24,2]] # defines a list \n", "print mylist\n", "print mylist[2] # refers to the third item \n", "print mylist[-1] # refers to the last item \n", "mylist[1]=26.3 # replaces the second item \n", "print mylist\n", "del mylist[3] # deletes the fourth element\n", "print mylist" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To slice out a chunk of the middle of a list try this. It takes items 2 and 3 out (note it takes out up to but not including the last item number - don’t ask me why)." ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[26.3, '400']" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newlist=mylist[1:3]\n", "newlist" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or, we can slice it this way which takes from the fourth item (starting from 0!) to the end:" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[42, [24, 2]]\n" ] } ], "source": [ "newlist=mylist[3:]\n", "print newlist" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To copy a list BEWARE! You can make a copy - but it isn’t an independent copy (like in, e.g., Fortran), but it is just another name for the SAME OBJECT, so:" ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "new\n" ] } ], "source": [ "mycopy=mylist \n", "mylist[2]='new' \n", "print mycopy[2] \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See how mycopy got changed when we changed mylist? To spawn a new list that is a copy, but an independent entity, try:" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "new\n" ] } ], "source": [ "mycopy=mylist[:]\n", "mylist[2]=1003\n", "print mycopy[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So now mycopy stayed the way it was, even as mylist changed." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### List methods" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is “object oriented”, a popular concept in coding circles. We’ll learn more about what that means later, but for right now you can walk around feeling smug that you are learning an object oriented programming language. O.K., what is an object? Well, mylist is an object. Cool. What do objects have that might be handy? Objects have “methods” which allow you to do things to them. Methods have the form: object.method()\n", "\n", "Here are an example:" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 2.0, '400', 'spam', 42, [24, 2], 'me too']\n" ] } ], "source": [ "mylist=['a',2.0,'400','spam',42,[24,2]]\n", "mylist.append('me too') # appends a string to mylist \n", "print mylist\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a complete list of methods for lists, see: http://docs.python.org/tutorial/datastructures.html#more-on-lists.\n", "\n", "More generally, if you want to get all of the possible methods for an object, you can use the dir() function." ] }, { "cell_type": "code", "execution_count": 98, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n", "L.append(object) -- append object to end\n" ] } ], "source": [ "print dir(mylist) # get all methods of mylist\n", "print mylist.append.__doc__ # get documentation for the list function \"append\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### More about strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numbers are numbers. While there are more kinds of numbers (complex, etc.), strings can be more interesting. (NB: The variable type is called \"string\" because it is a string of 0 or more characters). Unlike in some languages, they can be denoted with single, double or triple quotes: e.g., 'spam', “Sam’s spam”, or: \n", "\n", "\"\"\"\n", "\n", "Hi there - we can type as\n", "\n", "many lines as we want!\n", "\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'\\nHi there - we can type as\\nmany lines as we want!\\n'" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"\"\"\n", "Hi there - we can type as\n", "many lines as we want!\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings can be added together and sliced. But they CANNOT be changed in place - you can’t do this: newstring[0]='b'. To find more of the things you can and cannot do to strings, see: http://docs.python.org/tutorial/introduction.html#strings" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "spa\n" ] } ], "source": [ "newstring = 'spam' + 'alot'\n", "print newstring[0:3]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dictionaries!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries are denoted by {}. They are also somewhat like lists, but instead of integer indices, they use alphanumeric ‘keys’: I love dictionaries. So here is a bit more about them.\n", "\n", "To define one:" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "collapsed": false }, "outputs": [], "source": [ "Telnos={'lisa':46084,'lab':46531,'jeff':44707} # defines a dictionary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To return the value associated with a specific key:" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "46084" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Telnos['lisa']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To change a key value:" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "collapsed": true }, "outputs": [], "source": [ "Telnos['lisa']=46048" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To add a new key value:" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "collapsed": true }, "outputs": [], "source": [ "Telnos['newguy']=48888" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries also have some methods. One useful one is:" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['lisa', 'newguy', 'lab', 'jeff']" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Telnos.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a more complete accounting of dictionaries, see:\n", "http://docs.python.org/tutorial/datastructures.html#dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arrays in Python have many similarities to lists. Unlike lists, however, arrays have to be all of the same data type (dtype), usually numbers (integers or floats), although there appears to be something called a character array. Also, the size and shape of an array must be known a priori and not determined on the fly like lists. For example we can define a list with L=[], then append to it as desired, but not so arrays - they are much pickier and we’ll see how to set them up later.\n", "\n", "Why use arrays when you can use lists? They are far more efficient than lists particularly for things like matrix math. But just to make things a little confusing, there are several different data objects that are loosely called arrays, e.g., arrays, character arrays and matrices. These are all subclasses of ndarray. I’m just going to briefly introduce arrays here.\n", "\n", "Here are a few ways of making arrays:" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A= [[1 2 3]\n", " [4 2 0]\n", " [1 1 2]]\n", "B= [[0 1 2 3 4]\n", " [5 6 7 8 9]]\n", "C= [[1 2 3]\n", " [4 5 6]]\n", "d= [[ 0. 0. 0.]\n", " [ 0. 0. 0.]]\n", "E= [[ 1. 1. 1. 1.]\n", " [ 1. 1. 1. 1.]]\n", "= [ 0. 0.76923077 1.53846154 2.30769231 3.07692308\n", " 3.84615385 4.61538462 5.38461538 6.15384615 6.92307692\n", " 7.69230769 8.46153846 9.23076923 10. ]\n", "G= [[ 0. 0.]\n", " [ 0. 0.]]\n" ] } ], "source": [ "import numpy as np\n", "A= np.array([[1,2,3],[4,2,0],[1,1,2]]) \n", "print 'A= ', A\n", "B=np.arange(0,10,1).reshape(2,5) # guess what reshape() does!\n", "print 'B= ', B\n", "C=np.array([[1,2,3],[4,5,6]],np.int32) \n", "print 'C=', C\n", "D=np.zeros((2,3)) # Notice the zeros and the size is specified by a tuple. \n", "print 'd= ', D\n", "E=np.ones((2,4)) \n", "print 'E= ', E\n", "F=np.linspace(0,10,14) \n", "print '= ', F\n", "G=np.ndarray(shape=(2,2), dtype=float) \n", "print 'G= ', G # note how this is initalized with really low numbers (but not zeros). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the difference between linspace(start,stop,N) and arange(start,stop,step). The function linspace creates an array with 14 evenly spaced elements between the start and stop values while arange creates an array with elements at step intervals between the starting and stopping values. \n", "\n", "Python arrays have methods like dtype, ndim, shape, size, reshape(), ravel(), transpose() etc. \n", "\n", "Here are some particularly handy examples:\n" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "L= [[1, 2, 3], [4, 2, 0], [1, 1, 2]]\n", "A= [[1 2 3]\n", " [4 2 0]\n", " [1 1 2]]\n" ] } ], "source": [ "A = np.array([[1,2,3],[4,2,0],[1,1,2]]) \n", "L = A.tolist() # converts array A to list L\n", "print 'L=',L\n", "A = np.array(L) # converts list L to array A\n", "print 'A=',A" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a lot more tricks with arrays, go to the NumPy Reference website here: http://docs.scipy.org/doc/numpy/reference/\n", "\n", "See especially the rules for slicing and dicing: \n", "\n", "http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pandas" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that you have fallen in love with Python and Numpy, we have a new treat for you: Pandas. It supports elegant data structures and tools for wrangling the data which allow fast and user-friendly data analysis. There are two basic data structures: the Series (a one-dimensional array like object that is a data array with an associated array of indices which can be numbers or text) and the DataFrame (a spreadsheet like data table).\n", "\n", "First, invoke Pandas by importing it, then create some data Series using several approaches:" ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1\n", "1 2\n", "2 3\n", "3 4\n", "dtype: int64\n" ] } ], "source": [ "import pandas as pd\n", "# create first pandas object with numeric indices \n", "obj = pd.Series([1,2,3,4]) \n", "print obj" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "a 1\n", "b 2\n", "c 3\n", "d 4\n", "dtype: int64" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# create second pandas object with text indices \n", "obj2=pd.Series([1,2,3,4],index=['a','b','c','d'])\n", "obj2" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "jeff 44707\n", "lab 46531\n", "lisa 46048\n", "newguy 48888\n", "dtype: int64" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# create a third pandas Series from the dictionary\n", "obj3=pd.Series(Telnos)\n", "obj3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another very useful pandas object is the DataFrame. These have both row and column indices and are like a dictionary of Series so are much more flexible than the Numpy array objects. Here is an example:" ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
namesroomstelnos
0jeff300D RH44707
1lisa300E RH46531
2lab1162 SvH46084
\n", "
" ], "text/plain": [ " names rooms telnos\n", "0 jeff 300D RH 44707\n", "1 lisa 300E RH 46531\n", "2 lab 1162 SvH 46084" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data={'telnos':['44707','46531','46084'],\\\n", " 'names':['jeff','lisa','lab'],\\\n", " 'rooms':['300D RH','300E RH','1162 SvH']} \n", "frame=pd.DataFrame(data) \n", "frame " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many methods associated with pandas objects which allow searching, massaging and generally fiddling with the data. You should check out some of the many tutorials on pandas on the web." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code blocks" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any reasonable programming language must provide a way to group blocks of code together, to be executed under certain conditions. In Fortran, for example, there are if statements and do loops which are bounded by the statements if, endif and do, endo respectively. Many of these programs encourage the use of indentation to make the code more readable, but do not require it. In Python, indentation is the way that code blocks are defined - there are no terminating statements. Also, the initiating statement terminates in a colon. The trick is that all code indented the same number of spaces (or tabs) to the right belong together. The code block terminates when the next line is less indented. A typical Python program looks like this:\n", "\n", "program statement \n", "block 1 top statement: \n", "    block 1 statement \n", "    block 1 statement \\ \n", "        ha-ha i can break the indentation convention! \n", "    block 1 statement \n", "    block 2 top statement: \n", "        block 2 statement \n", "        block 2 statement \n", "        block 3 top statement: \n", "            block 3 statement \n", "            block 3 statement \n", "            block 4 top statement: block 4 single line of code \n", "        block 2 statement \n", "        block 2 statement \n", "    block 1 statement \n", "    block 1 statement \n", "program statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exceptions to the code indentation rules are:\n", "\n", "* Any statement can be continued on the next line with the continuation character \\ and the indentation of the following line is arbitrary.\n", "* If a code block consists of a single statement, then that may be placed on the same line as the colon.\n", "* The command break breaks you out of the code block. Use with caution!\n", "* There is a cheat that comes in handy when you are writing a complicated program and want to put in the code blocks but don’t want them to DO anything yet: the command pass does nothing and can be used to stand in for a code block.\n", "\n", "In the following, I’ll show you how Python uses code blocks to create “do” and “while” loops, and “if” statements.\n", "\n", "But first a few more basics: \n", "* len(mylist) returns the number of items in the list mylist\n", "* range(start,stop,increment) returns a list of integers from start to stop MINUS ONE, in increments of inrement." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### For blocks" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42\n", "spam\n", "ocelot\n", "Done with first way\n", "42\n", "spam\n", "ocelot\n", "All done\n" ] } ], "source": [ "mylist=[42,'spam','ocelot']\n", "\n", "# Pythonic way\n", "for item in mylist:\n", " print item\n", "print 'Done with first way'\n", "\n", " \n", "# less-Pythonic, but still acceptable\n", "for i in range(0, len(mylist), 1):\n", " print mylist[i]\n", "print 'All done'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that of course we could have used any variable name instead of `item', but it makes sense to use variable names that mean what they do." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is an example with a little more heft to it. It creates a table of trigonometry functions, spitting them out with a formatted print statement:\n" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0.0 1.0000 0.0000 0.0000\n", " 1.0 0.9998 0.0175 0.0175\n", " 2.0 0.9994 0.0349 0.0349\n", " 3.0 0.9986 0.0523 0.0524\n", " 4.0 0.9976 0.0698 0.0699\n", " 5.0 0.9962 0.0872 0.0875\n", " 6.0 0.9945 0.1045 0.1051\n", " 7.0 0.9925 0.1219 0.1228\n", " 8.0 0.9903 0.1392 0.1405\n", " 9.0 0.9877 0.1564 0.1584\n" ] } ], "source": [ "import numpy as np\n", "deg2rad = np.pi/180. # remember conversion to radians from degrees\n", "for theta in range(90): # short form of range, returns [0,1,2...89]\n", " ctheta = np.cos(theta*deg2rad) # define ctheta as cosine of theta\n", " stheta = np.sin(theta*deg2rad)# define stheta as sine of theta\n", " ttheta = np.tan(theta*deg2rad) # define ttheta as tangent of theta\n", " if theta<10:\n", " print '%5.1f %8.4f %8.4f %8.4f' %(theta, ctheta, stheta, ttheta) \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make the output look nice, we do not use\n", "\n", "\n", "print theta, ctheta, stheta, ttheta\n", "\n", "\n", " which would space the numbers irregularly among the columns and put out really long numbers. Instead,\n", "we explicitly specify the output format. The output format is given in the quotes. The format for each\n", "number follows the %, 5.1f is for 5 spaces of floating point output, with 1\n", "space to the right of the decimal point. The single\n", "blank space between %5.1f and %8.4f is included in the output, in fact any\n", "text there is reproduced exactly in the output, thus to put commas between\n", "the output numbers, write:\n", "\n", "print '%5.1f, %8.4f, %8.4f, %8.4f' %(theta, ctheta, stheta, ttheta)\n", "\n", "Tabs ($\\backslash$t) would be formatted like this:\n", "\n", "\n", "print '%5.1f '\\t' %8.4f'\\t' %8.4f,\\t' %8.4f' %(theta, ctheta, stheta, ttheta)\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### If and while blocks" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The \"for block\" is just one way of controlling flow in Python. There are also if and while code blocks. These execute code blocks the same way as for loops (colon terminated top statements, indented text, etc.). For both of these, the code block is executed if the top statement is TRUE. For the \"if\" block, the code is executed once but in a \"while\" block, the code keeps executing as long as the statement remains TRUE.\n", "\n", "The key to flow control therefore is in the top statement of each code block; if it is TRUE, then execute, otherwise skip it. To decide if something is TRUE or not (in the boolean sense), we need to evaluate a statement using comparisons. Here's a handy table with comparisons (relational operators) in Python:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* equals:        ==\n", "* does not equal:         !=\n", "* less than:         <\n", "* less than or equal to:          <=\n", "* greater than:         >\n", "* greater than or equal to:          <=\n", "* and:          and\n", "* or:          or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These operators can be combined to make complex tests. Here is a juicy complicated statement:\n", "\n", "if ( (a > b and c <= 0) or d == 0): \n", "    code block " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use parentheses liberally - make the order of operation completely unambiguous even if you could get away with fewer.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Finer points of if blocks: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are whistles and bells to the ‘if’ code blocks. In Python these are: elif and else. A code block gets executed if the top if statement is FALSE and the elif statement is TRUE. If both the top if and the elif statements are FALSE but the else statement is TRUE, then Python will execute the block following the else. Consider these examples:" ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "It's a get together\n" ] } ], "source": [ "mylist=['jane', 'brian','denise']#, 'john', 'fred'] \n", "\n", "if len(mylist) > 4:\n", " print \"It's a party\"\n", "elif len(mylist) > 2:\n", " print \"It's a get together\"\n", "elif len(mylist) == 2:\n", " print \"It's a date\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### While loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As already mentioned, the ‘while’ block continues executing as long as the while top statement is TRUE. In other words, the if block is only executed once, while the while block keeps looping until the statement turns FALSE. Here are a few examples:" ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "I'm done counting!\n" ] } ], "source": [ "a=1 \n", "while a < 10: \n", " print a \n", " a+=1 \n", "print \"I'm done counting!\"\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## File I/O in Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python would be no better than a rather awkward graphing calculator (and we haven’t even gotten to the graphing part yet) if we couldn’t read data in and spit data out. You learned a rudimentary way of spitting stuff out already using the print statement, but there is a lot more to file I/O in Python. We would like to be able to read in a variety of file formats and output the data any way we want. In the following we will explore some of the more useful I/O options in Python.\n", "\n", "You can read data in using the native Python function 'readlines()', the NumPy function 'np.loadtxt()' or the Pandas function 'pd.read_csv()'. Each of these has strengths and weaknesses. The function readlines() reads everything in as strings. loadtxt() reads things into arrays and has to be all of the same variable type (you can't mix numbers and strings). And read_csv() takes some getting used to (but is totally worth it). \n", "\n", "Now we will create a data set, write it to a file and read it back in using all three methods. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Writing data to a file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can read data in using the native Python function 'readlines()', the NumPy function 'loadtxt()' or the Pandas function 'read_csv()'. Each of these has strengths and weaknesses. The function readlines() reads everything in as strings. loadtxt() reads things into arrays and has to be all of the same variable type (you can't mix numbers and strings). And read_csv() takes some getting used to (but is totally worth it). \n", "\n", "Remember the Pandas dataframe 'frame'? " ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " names rooms telnos\n", "0 jeff 300D RH 44707\n", "1 lisa 300E RH 46531\n", "2 lab 1162 SvH 46084\n" ] } ], "source": [ "print frame" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's write it to a tab delimeted file (filename 'data.txt'). The default column separator is a comma (hence the csv which stands for comma separated value), but many separators are possible. To specify a tab, use \"sep='\\t'\". To do it without the sometimes annoying incices, specify index=False. " ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "collapsed": false }, "outputs": [], "source": [ "frame.to_csv('data.txt',sep='\\t',index=False) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can look at your handy work with some text editor (Notepad, Textedit, vi!). Then read it back in with Pandas. To specify a header line, use header=0 for the first line, 1 for the second.... " ] }, { "cell_type": "code", "execution_count": 79, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
namesroomstelnos
0jeff300D RH44707
1lisa300E RH46531
2lab1162 SvH46084
\n", "
" ], "text/plain": [ " names rooms telnos\n", "0 jeff 300D RH 44707\n", "1 lisa 300E RH 46531\n", "2 lab 1162 SvH 46084" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newframe=pd.read_csv('data.txt',sep='\\t',header=0)\n", "newframe" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So far you have learned how to use functions from program modules like NumPy. You can imagine that there are many bits of code that you might write that you will want to use again and again, say converting between degrees and radians and back, or finding the great circle distance between two points on Earth. The basic structure of a program with a Python function is:" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "oh boy\n" ] }, { "data": { "text/plain": [ "42" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def FUNCNAME(in_args):\n", " \"\"\"\n", " DOC STRING - says what it does!\n", " \"\"\"\n", " print in_args\n", " out_args=42 # some code that does something\n", " return out_args # returns some stuff\n", "FUNCNAME('oh boy')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Finer points of functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first line must have ’def’ as the first three letters, must have a function name with parentheses and a terminal colon. If you want to pass some variables to the function, they go where in_arg sits, separated by commas. There are no output variables here.\n", "\n", "There are four different ways to handle argument passing.\n", "\n", "1) You could have a function that doesn’t need any arguments at all:\n", "\n" ] }, { "cell_type": "code", "execution_count": 81, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def gimmepi():\n", " \"\"\"\n", " Returns the value of pi\n", " \"\"\"\n", " import numpy as np\n", " return np.pi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you call it, you get some pi!" ] }, { "cell_type": "code", "execution_count": 82, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.14159265359\n" ] }, { "data": { "text/plain": [ "3.141592653589793" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pi=gimmepi()\n", "print pi\n", "# or just this:\n", "gimmepi()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2) You could use a set list of what are called ‘formal’ variables that must be passed:" ] }, { "cell_type": "code", "execution_count": 83, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def deg2rad(degrees): \n", " \"\"\"\n", " converts degrees to radians\n", " \"\"\"\n", " return degrees*gimmepi()/180." ] }, { "cell_type": "code", "execution_count": 84, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42 degrees in radians is: 0.733038285838\n" ] } ], "source": [ "print '42 degrees in radians is: ',deg2rad(42.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3) You could have a more flexible need for variables. You signal this by putting *args in the in_args list (along with any formal variables you want):" ] }, { "cell_type": "code", "execution_count": 85, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "you sent me these arguments:\n", "1\n", "4\n", "hi there\n" ] } ], "source": [ "def print_args(*args):\n", " \"\"\"\n", " prints the argument list\n", " \"\"\"\n", " print 'you sent me these arguments:'\n", " for arg in args:\n", " print arg\n", "print_args(1,4,'hi there')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "4) You can use a keyworded, variable-length list by putting **kwargs in for in_args:" ] }, { "cell_type": "code", "execution_count": 86, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def print_kwargs(**kwargs):\n", " \"\"\"\n", " prints a keyworded list of arguments\n", " \"\"\"\n", " for key in kwargs:\n", " print '%s %s'%(key,kwargs[key])\n" ] }, { "cell_type": "code", "execution_count": 87, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arg1 NI!\n", "arg2 42\n", "arg3 ocelot\n" ] } ], "source": [ "print_kwargs(arg1='NI!',arg2=42,arg3='ocelot')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Doc string" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although you can certainly write functional code without a document string, make a habit of always including one. Trust me - you’ll be glad you did. This can later be used to remind you of what you thought you were doing years later. It can be used to print out a help message by the calling program and it also let’s others know what you intended. Notice the use of the triple quotes before and after the documentation string - that means that you can write as many lines as you want." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Function body" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This part of the code must be indented, just like in a for loop, or other block of code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Return statment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You don’t need this unless you want to pass back information to the calling body (see, for example print_kwargs() above). Python separates the entrance and the exit. See how it can be done in the gimme_pi() example above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Main program as a function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is considered good Python style to treat your main program block as a function too. (This helps with using the document string as a help function and building program documentation in general.) In any case, we recommend that you just start doing it that way too. In this case, we have to call the main program with the final two lines. (The code \"if \\__name\\__ == \"\\__main\\__\":\" prevents the code from running if you just import the module -- don't worry about the \"why\" too much, but this syntax is a good habit to get into)." ] }, { "cell_type": "code", "execution_count": 88, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "arg1 NI!\n", "arg2 42\n", "arg3 ocelot\n" ] } ], "source": [ "def main():\n", " \"\"\"\n", " calls function print_kwargs\n", " \"\"\"\n", " print_kwargs(arg1='NI!',arg2=42,arg3='ocelot') # defined above\n", " \n", "#LJ to be fully proper:\n", "if __name__ == \"__main__\":\n", " main() # runs the main program" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Build your own module\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how in the above examples, all the functions preceded the main function. This is because Python is an interpreter and not compiled - so it won’t know about anything declared below as it goes through the script line by line. On the other hand, we’ve been running lots of functions and they were not in the program we used to call them. The trick here is that you can put a bunch of functions in a separate file (in your path) and import it, just like we did with NumPy. Your functions can then be called from within your program in the same way as for NumPy.\n", "\n", "So let’s say we put all the above functions in a file called myfuncs.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Put this into a text file in your homework directory: you can copy it and then use the unix (or dos) command 'cat > myfuncs.py' (remember the ^D at the end). \n", "\n" ] }, { "cell_type": "code", "execution_count": 89, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def gimmepi(): \n", " \"\"\"\n", " returns pi\n", " \"\"\"\n", " return 3.141592653589793\n", "def deg2rad(degrees): \n", " \"\"\"\n", " converts degrees to radians\n", " \"\"\"\n", " return degrees*3.141592653589793/180.\n", "def print_args(*args):\n", " \"\"\"\n", " prints argument list\n", " \"\"\"\n", " print 'You sent me these arguments: '\n", " for arg in args:\n", " print arg\n" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "collapsed": false }, "outputs": [ { "ename": "ImportError", "evalue": "No module named myfuncs", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mImportError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mmyfuncs\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mmf\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mImportError\u001b[0m: No module named myfuncs" ] } ], "source": [ "import myfuncs as mf" ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "collapsed": false }, "outputs": [ { "ename": "NameError", "evalue": "name 'mf' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgimmepi\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'mf' is not defined" ] } ], "source": [ "mf.gimmepi()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matplotlib" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So far you have learned the basics of Python, and NumPy. But Python was sold as a way of visualizing data and we haven’t yet seen a single plot (except a stupid one in the beginning). There are many plotting options within the Python umbrella. The most mature and the one we am most familiar with is matplotlib, a popular graphics module of Python. Actually matplotlib is a collection of a bunch of other modules, toolkits, methods and classes. For a fairly complete and readable tour of matplotlib, check out these links:\n", "http://matplotlib.sourceforge.net/Matplotlib.pdf\n", "and here:\n", "http://matplotlib.sourceforge.net/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### A first plot" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's start by reviewing a simple plot script. But first we must import a few more modules to let us plot within the notebook." ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib\n", "import pylab as plt\n", "%matplotlib inline " ] }, { "cell_type": "code", "execution_count": 93, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAA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I8A/G/ZEpH5zgZCWqPM3fX8dOAW4yL8ep0njAiEt3ceZ/UM3DwN/Anxo\nyPOR+soFQlqCJG8DvldVX+7c9WfAq5L8yhCnJfWVn2KSJPVkQUiSenKBkCT15AIhSerJBUKS1JML\nhCSpJxcISVJPLhCSpJ5cICRJPf1/jrJMBi57A5MAAAAASUVORK5CYII=\n", "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "X=[1,2,3] # define x variables\n", "Y=[2,4,6] # define y variables\n", "plt.plot(X,Y)# makes a line\n", "plt.plot(X,Y,'ro') # makes some little red circles\n", "plt.xlabel('X') # prints the X axis label\n", "plt.ylabel('Y') # figure it out yourself!\n", "plt.title('Boring plot') # ditto" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course there is lots more to learn about Python! We will embellish your skills in the next homework problems and of course there is abundant material online to learn from. \n", "\n", "For your homework for this class, download this notebook and work through it.\n", "Get the notebook here:\n", "http://magician.ucsd.edu/~ltauxe/sio247/\n", "\n", "Play with it. Run each cell block as you go or try to run them all at once (figure out how to debug the problem that you encounter doing that.) The next homework will be to write an actual original notebook with markdown and code so get ready!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }