Math 450 Laboratory 1

Introduction to python programming at PSU

Wednesday, 11:15-12:05, 2016-01-20, Osmond 216


Goals for this laboratory...

Getting Started...

Check to see if your Mac workstation is turned on. If it is not on, please turn it on.

Login with your PSU id and password.

The first thing we need to do is get out of this gui to a terminal that shows a command line. Using the magnifying-glass "Find" button in the menu bar at the top right, search for an application called "Terminal". Drag this to the Dock so it will be convenient.

Run "Terminal". This will open up a "terminal window", and the program running inside the window is called a "shell". A Shell is the generic term used in the biological sense - a simple and tough thing surrounding the important stuff. For example, your body is a shell for your mind. In this context, we are using a Unix shell. There are around 10 different unix shells that people use, and that you might want to explore once you become more familiar.

The UNIX shell command line

Welcome to the command line. In the terminal window, there should be a line of text something like "$" This is called a command prompt. Different shells usually have different prompts. The Bourne again shell (bash) is the default shell and uses a "$" for its prompt usually. But what it is doesn't really matter. The important thing is that there is a cursor next to it. If you start typing, that's where things will appear.

The command-line is the oldest computer interface in use, and is incredibly powerful (Before 2001, macs did not have a command-line interface. Windows dropped their's in 1995, and brought it back in 2006), but also a little scary because of it's arcane and obscure syntax. Fortunately, only a few commands are important for us right now.

There are many features in the shell to make your life easier -- if you can think of it, somebody has probably made it possible. For example, you can use the UP ARROW to go back through your history of commands you've already run, so you don't have to re-type long commands. The TAB key can be used for autocompletion often. For more information about common commands and magical incantations, see this cheat-sheet or that cheat-sheet. And remember, google is your friend.

Python

At the shell prompt in the terminal, type

$ cd
$ cd Desktop
$ python

These commands tell the unix shell to change the current working directory to the Desktop and to run the Python interpretter. You can exit the python interpretter back to the unix shell at any time with exit() or the key combination CTRL-d (which is the character traditionally marking the end of a file).

Python is a 5th-generation computer language that was created in the late 80's by Guido van Rossum, and becoming popular around 2001 (when I learned it). It is easier to work with than many other languages, but also more flexible, having a variety of linguistic constructs not available in other languages. It gained popularity after the turn of the century as a free and flexible tool for general purpose scientific computing.

Here are some links that might be nice references tonight and in the future, but you should probably skip for right now.

Python's interpretter

Like any command-line shell, python's interpretter evaluates instructions you enter at the >>> prompt. In this case, the instructions expressed in the python language. Type the following commands into the python prompt and observe the results.

First, python does simple arithmetic like a calculator...

>>> 2+3
>>> 2*3
>>> 2**3
>>> 7^2

Note that ** is used for exponentiation in python, while ^ is used for bit-wise negation (a boolean operation -- if you don't know what it is, do not worry, you do not need to know).

Python uses variables to store things in memory.

>>> x = 13
>>> y = x - 5
>>> print y

Here, we have also introduced the command print, which is one of about 30 reserved words that makes up the python language. Really, it's true, the whole language has only 30 words! Here is a slightly more complicated example of how pring can be used with strings and inputs.

>>> print "Hello, World"
>>> name = raw_input("What is your name? ")
>>> print name
>>> print "Hello, %s.  Nice to meet you."%name

In the two cases above, x, y, and name are "variables". Variables in python are "dynamically typed", which means they can store many different kinds of things, and you just have to remember what kind of thing is in each one as you program. Python has a few basic variable types built in, and a simple class system for creating more of your own.

Getting help

One of the big improvements of python over preceeding languages was the use of in-line documentation of code. This can be accessed in two easy ways.

Help commands are your friends. Use them early and often.

Better python tools - editors, ipython and Canopy

In practice, people don't use "python" for interactive work -- just to run their programs. If you put a bunch of python commands in a file "mycmds.py" and do

    $ python mycmds.py

those commands will be run, and you'll see any outputs from print commands.

Many people like me use fancy text-editors to program, which is the root of the editor wars.

For interactive work, we usually use a tool with more bells and whistles. The most commonly used interprettor for interactive work is ipython. It colorizes input, tracks input and output for future reference, allows customization, and a bunch of other useful things. (Ipython uses a different prompt from ">>>". I'll keep using ">>>" from here on, just to signify python input, but you can type the commands into any python interprettor).

Recently, Enthought has pulled together a nice GUI called Canopy for interactive scientific computing with python. Canopy is free to students at university like you, and is what we'll mostly use. There is also an alternative, called Anaconda by Continuum Analytics.

Writting your first script

Because it is tedious to write out lengthy instructions every time you want to program a task, we usually save our commands to a file called a "script". Below is a simple program that prints a table for converting between Celcius and Farenheit.

  1. Open up "Canopy" (it is slow starting up the first time - be patient).

  2. Go to an "Editor" window. There will be several sub-windows. On the left is a file browser. On the top is an editor window. On the bottom is a command line interprettor window. Up top there is a button to "run" your code.

  3. Enter the following code into the editor window. This is what we call a script.

    print '-- My Celcius-to-Farenheit table -----'
    C = -20
    dC = 5
    while C <= 40:
        F = (9.0/5)*C + 32
        print C, F
        C = C + dC
    print '--------------------------------------'

    The new thing in this code is that it uses a "while"-loop. A while-loop tells the computer to keep doing a particular thing as long as the condition it is given holds true. In this case, as long as the temperature in C is less than or equal to 40 degrees.

  4. Save your new script as "c2f.py". Be sure to keep track of which directory you are saving it to. The Desktop is usually the best place at first. Hint: Generally, it is best not to include spaces or punctuation other than '_' or '.' in file names.

  5. Make a prediction about what you think will happen when you run this script.

  6. Click the "run" button to run the script. Does the output match your predictions?

  7. You can also run your script from the terminal without having to use Canopy. In a new terminal window, "cd" to the directory where you saved "c2f.py" and do

    $ python c2f.py

    The output you get should be the same as what you saw in Canopy.

  8. Switch back to Canopy.

Writting your first function

In most modern computer languages, functions are used regularly. A function in python is a piece of code that takes 1 or more arguments, and returns 1 or more results. Functions begin with the keyword def and finish with the keyword return followed by whichever variables you want to return. Try the following script, which I call "c2fv2.py"

def CtoCF(C):
    F = (9.0/5)*C + 32
    return C, F

print '---'
C = -20
dC = 5
while C <= 40:
    print CtoCF(C)
    C = C + dC
print '---'

SAVE YOUR WORK TO YOUR PASS DIRECTORY!

On the Desktop, grab your new scripts and drag them to your PASS directory. If you do not save your scripts like this, they may be lost and gone forever after you log out.

A very good idea is to get a 500 mg or larger USB stick, on which you can keep all your python work with you at all times! That way, you can drop into any lab or computer and work at any time if you feel like it.