Introduction to python programming

( previous, home, next )


Goals for this laboratory…

Getting Started…

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

Login with your PSU id and password.

If at home you have a Mac or Linux OS, you may want to familiarize yourself with the UNIX shell command line. A brief overview is given at the bottom of this page. Since we’re in a Windows computer lab is we’ll focus on that OS feature today.

The first thing that we need to do is open Spyder. Open the Main Menu, then select the Search item, and search for “spyder”. Click on the result you find.

A “welcome” window will open; it may take some time to load the first time. Once open, you should see a window similar to this …

A screenshot of spyder's development window

On the left is a space where you can edit Python scripts, and the bottom right is the Python intepreter from which you can perform simple calculations or run Python scripts, and on the top is a tabbed window with tabs labelled “Variable explorer”, “File explorer”, and “Help”.

In the Python interpreter window there’s a prompt,

[Show code]
In [1]: 

(why it’s “1” is discussed below). You can navigate the file tree from this prompt. To run your scripts you need the application to be looking in the right folder for them! A few commands (that are also UNIX shell commands) will help:

Navigate to your UDrive account, `cd V:' Remember that V: is your personal UDrive account.

Make the new folder. Then move into that directory, cd PythonPractice\.

You can save your work to this folder. Since it’s your UDrive personal directory, your work won’t get lost!

Python

Python is a 5th-generation computer language that was created in the late 80’s by Guido van Rossum. 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. Today, it is one of the most widely used tools in the world.

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

Python’s interpreter

The thing we call “Python” has a few parts. The “thing” that is python is what we call an “interpreter” (bottom right). Python’s interpreter evaluates instructions you enter at the In [ ]: 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…

[Show code]
In [1]: 2+3
In [2]: 2 * 3
In [3]: 2 ** 3
In [4]: 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).

Note that the input numbers are increasing. That’s because Python remembers all inputs and outputs and stores them in an array (vector); the numbers are the vector index. You can “recall” old inputs and outputs at any time:

[Show code]
In [5]: In[4]
In [6]: Out[4]

Because we make mistakes and numbering the prompts can create confusion, I’m going to stop using them here. In the core version of the python interpretter, “>>>” is used instead to mark the prompt. From now on in the notes, I’ll use “>>>” to avoid issues with numbering each line, so remember that “>>>” is the same as “In [ * ]:” where * is an integer.

Python uses variables to store things in computer memory.

[Show code]
>>> x = 13
>>> y = x - 5
>>> print(y)

Here, we have also introduced the function print, which used to be one of the few reserved words that makes up the python language. Really, the whole language is based on only 33 words! Here is a slightly more complicated example of how print can be used with strings and inputs (answer the question, when it get’s asked).

[Show code]
>>> print("Hello, World")
>>> name = input("What is your name? ")
>>> print(name)
>>> print("Hello, %s. Nice to meet you. Would you like to play a game?"%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.

Warning: not all variables work the same

In python, there is an important difference between certain kinds of variables that you might not notice at first but can cause you hours of headaches if you aren’t warned. Some variables behave like the values they are assigned, but other variables behavie like references to their objects. In math, we expect variables to behavie like their values. Variables representing numbers and other “immutable” things do behavie that way.

>>> x = 1
>>> y = x
>>> x = 3
>>> x
>>> y

As you might expect, you get out 3 for x and 1 for y. However, variables representing lists, arrays, matrics, dictionaries, and other “mutable” things actually act as references to their values rather than the values themselves.

>>> a = [1, 2]
>>> b = a
>>> a
>>> b
>>> b[0] = 3
>>> a
>>> b

Notice that you only changed list b’s initial element to 3, but the inital value of list a also changed to 3! This is because the assignment b = a copied a’s reference of the list, rather than the list itself. So a and b were both referring to the same list, and when you changed an entry using a, then variable b also sees the change. There are several ways to work around this if you want to. One is to explicitly create a new list from the old one.

>>> c = [4, 5]
>>> d = list(c)
>>> d[0] = 6
>>> c
>>> d

But, beware! If you have reference variables inside your list, like a list of lists, the your new list may give rise to the same bug! There is a special python function called deepcopy() designed to help with these issues. This bug is common for beginners working with data, arrays, and matrices. You will always need to be vigilant.

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. Google or your favorite search engine too!

Writing 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. Select “New file” from the File menu.

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

    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.

  3. Save your new script as “c2f.py”. Be sure to keep track of which directory you are saving it to. Our new “PythonPractice” directory is probably the best place. The UDrive directory or Desktop are also common places. Hint: Generally, it is best not to include spaces or punctuation other than ’_‘or’.’ in file names.

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

  5. Now, you can run your script. You can run the script in two ways:

    Does the output match your predictions?

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. This is much like the mathematical functions: in \(z=f(x,y)\), the function \(f\) takes in \(x\) and \(y\) as the arguments, and returns a result that we name \(z\). Functions begin with the keyword def and finish when they reeach the keyword return followed by whichever variables have the results you want to return. Try the following script, which I call “c2fv2.py”

[Show code]
def CtoCF(C):
    # a function to convert Celsius to Farenheit
    #   takes a temperature in Celsius units as one argument
    #   returns a tuple with two temps, celsius and farenheit
    F = (9.0/5)*C + 32
    return (C, F)

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

MAKE SURE THAT YOU’VE SAVED YOUR WORK TO YOUR UDrive DIRECTORY!**

If you haven’t, grab your new scripts and drag them to your UDrive directory (or, if you prefer, your PASS directory). If you do not save your scripts like this, they may be lost and gone forever after you log out.

A good idea is to get a 500 Meg or larger USB stick, on which you can back up all your python work and have 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. Of course, the down side is that you might lose it. Caveate emptor.

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

    V:\PythonPractice> python c2f.py

at the Windows command prompt, or

    $ python c2f.py

from the standard terminal shell in Mac/Linux OS, 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 tools with more bells and whistles.

For Macs or Linux OS: The UNIX shell command line

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.

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 theirs in 1995, and brought it back in 2006), but also a little scary because of its 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.

To open Python…

At the shell prompt in the terminal, type

[Show code]
$ cd
$ cd Desktop
$ python

These commands tell the unix shell to change the current working directory to the Desktop and to run the Python interpreter. You can exit the python interpreter 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).

You can also run your script from the terminal or Windows command prompt without having to use Canopy. In a new terminal window, “cd” to the directory where you saved “c2f.py” and do

    $ python c2f.py

Or at the Windows command prompt, “cd” to the directory where you saved “c2f.py” and do

    C:\FileTree> python c2f.py
    

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

Exercises

  1. The proper way to test if x is one of two numbers 1 and 2 is
[Show code]
>>> x in (1, 2)
However, sometimes beginners mistakely write things like
[Show code]
>>> x = 1
>>> x == 1 or 2
>>> x == 2 or 1
>>> x == 2 or 3
>>> 0 or 1 == x
Explain the outputs of the code below using python's the
concepts of operator precidence and truth-value.

( previous, home, next )