3. The bare minimum Python to get started
3.1 Python through the interpreter and at the terminal
There are several ways inwhich you can interact with the Python programming language. Because it is an interpreted language, interacting with the interpreter through a shell or terminal environment is the most direct way. You can do this in one of several ways:
- Open Canopy and then open an editor. At the bottom of your editing window, you will notice a terminal-like environment. This environment is actually an ipython session. We will go over other details regarding ipython as we need some of its features. For now you can just consider it a normal python environment.
- If you work in a Mac OS X environment, open a Terminal window and then type ‘python’ in the shell. Hit ‘return’. You are now in a python environment.
- If you work in Linux, open your favorite console, e.g. konsole in KDE, and type ‘python’ and hit ’return. You are now in a python environment.
- If you are in Windoze, all bets are off.
You can also interact with python by calling a program/script in a terminal using
$ python name_of_script.py
You can also use ipython, which is kinda the best of both worlds as you will see later on.
3.1.1 Python as a calculator
One of the first, and easiest things that you can do is use python as a calculator. Try it. You can type in a simple arithmetical operation and instantly receive an answer:
>>> 1 + 1
2
>>> 2 - 1
1
>>> 2 * 2
4
>>> 3 / 2
1
Uh, what happened there? Clearly python can’t do simple math…or can it? It turns out that python is very specific about is operators and data types. If you only use integers, it will do integer math. So remember to use decimals if you mean to use decimals. Just make it a habit…trust me.
3.2 Operators
- Arithmetic operators
| operator | function |
|---|---|
| * | multiply |
| / | divide |
| + | add |
| - | subtract |
| ** | power |
| % | modulus |
| // | floor division |
- Comparison operators
| operator | function |
|---|---|
| == | is equal to (not the same as = !!!) |
| != | is not equal to |
| <> | is not equal to |
| > | is greater than than |
| < | is less than |
| >= | is greater than or equal |
| <= | is less than or equal |
- Assignment operators
| operator | function |
|---|---|
| = | assigns from left side to right side |
| += | add to and then assign |
| -= | subtract from and then assign |
| *= | multiply by then assign |
| /= | divide by then assign |
| %= | modulus by then assign |
| //= | floor division by then assign |
| **= | power to then assign |
- Logical operators
| operator | function |
|---|---|
| and | logical and |
| or | logical or |
| not | logical not |
- Membership and identity operators
| operator | function |
|---|---|
| in | determines if something is in a sequence |
| not in | determines if something is not in a sequence |
| is | determines if two things point to the same object |
| is not | determines if two things do not point to the same object |
- Operator precedence
| operator | description |
|---|---|
| ** | exponentiation |
| * / % // | multiply, divide, modulus, floow |
| + - | add, subtract |
| <= < > >= | comparison operators |
| <> == != | equality operators |
| = %= /= //= += -= = *= | assignment operators |
| is is not | identity operators |
| in not in | membership operators |
| not or and | logical operators |
3.3 Data types
OK, back to why 3/2 does in fact equal 1. That is because you performed integer math. Never heard of that? Well remember it. It will play havoc with your programs. It also will affect all other arithmetic operators. Basically, integers do not have decimal parts, so python ignores them (most of the time). Integers aren’t the only data types that python knows.
We will use:
numeric types: int, float, long, complex sequence types: str, list, tuple, range set types: set mapping types: dict file objects, and more….
3.3.1 Numerical types
Numeric types largely determine the precision of the numbers that you use. Increasing precision requires more memory. In the old days this mattered. You were selfish with your longs, floats, and doubles. Today with all the memory that your computers have, this is less of a worry. So go ahead, play with your types.
3.3.2 Sequence types
Strings, lists, tuples, and dictionaries are your friends. They hold the data that you will use in your programs.
We will deal with several sequence types, mainly strings and lists.
3.3.2.1 Strings
Strings are lists of characters, like:
>>> a = 'Mike'
>>> print a
Mike
3.3.2.2 Lists
Lists are a type of object that hold elements. Elements can be numbers, text, classses…just about anything. In fact, a string is a list of characters. Here is an example of a list holding numerical data:
>>> data = [1, 2, 3, 4, 5]
>>> print data
[1,2,3,4,5]
So how is this useful? As will see in a bit, we can read data from files into lists and then perform tasks on these lists.
There are several useful things that you can do with lists: indexing, sorting, popping, appending, slicing.
3.3.2.3.1 indexing and slicing
Indexing is a way to access different elements of a list. Index counting starts at 0. This tye of counting will feel a little unnatural at first, but you’ll get used to it. Here are some basic examples of indexing:
>>> a = [1, 2, 3, 4, 5]
>>> a[0]
1
>>> a[2]
3
>>> a[-1]
5
>>> a[-3]
4
>>> a[3]
4
Slicing allows you to access sections of your list:
>>> a = [1, 2, 3, 4, 5]
>>> a[1:] # everything to the right beginning at position 1
[2, 3, 4, 5]
>>> a[:1] # everything to the left beginning at position 1
[1]
>>> a[1:3] # everything beginning at position 1 but ending right before position 3
[2, 3]
>>> a[1:2]
[2]
>>> a[1]
2
Note the differnce for the last two, a[1:2] is not equivalent to a[1]. The former returns a list, the latter, an element.
3.3.2.2.2 sorting
Sorting os what you think it is. Here is an example of how to sort a list in ascending or descending order:
> a = [4,2,5,3,7]
> a.sort()
> print a
[2, 3, 4, 5, 7]
> a.sort(reverse=True)
> print a
[7, 5, 4, 3, 2]
3.3.2.2.3 popping
Popping gets rid of things. If you have a list, typing the name of the list immediately followed by a period and the pop() will cause the last element of the list to be removed:
> a = [0, 1, 2, 3, 4, 5]
> a.pop()
> print a
[0, 1, 2, 3, 4]
You can also specify which element that you want to pop:
> a= [0, 1, 2, 3, 4, 5]
> a.pop(0)
> print a
[1, 2, 3, 4, 5]
> a.pop(1)
> print a
[1, 3, 4, 5]
Where do the elements go? They disappear unless you assign them to something:
> a = [1, 2, 3, 4, 5]
> b = a.pop()
> print a
[1, 2, 3, 4]
> print b
5
3.3.2.2.4 appending Appending is something that you will want to do regularly. For instance, maybe you have a list of data that you want to pass through some operation and put the result in another list.
> svl = [56, 47, 68, 72, 59, 63, 65]
> mass = []
> for i in svl:
> mass.append(0.1*svl)
> print mass
> [5.6, 4.7, 6.8, 7.2, 5.9, 6.3, 6.5]
3.4 Standard I/O
Here are a few commands that will help with user interactions. First the print statement. It does what you think that it does. It prints things to the screen. Go ahead, try it:
> print 'Hello world'
Hello world
> answer = 42
> print answer
42
> print "Answer to the Ultimate Question of Life, the Universe, and Everything is ", 42, "."
Answer to the Ultimate Question of Life, the Universe, and Everything is 42.
Pretty easy. Later on, we will deal with some specifics regarding formatting numbers, but this is enough to get you started. input and raw_input are means for the user to input data to the program.
3.5 Using libraries
Many useful functions have been written to help with many tasks. You can find a list of the standard functions and libraries that come with Python v. 2.7 here. Libraries that you will most definitely use are math, csv, and random. Definitely check out what python already does out of the box.
To call functions from different libraries, you have many different options. First, you an import the library and call a function like this:
> import math
> math.sin(3.14)
0.0015926529
> math.sin(math.pi) # the math library even has useful constants
1.224646799e-16
You can also call all of the functions at once:
> from math import *
> cos(pi)
-1.0
You can call one or more function and even rename it:
> from math import degrees
> degrees(math.pi)
180.0
> from math import degrees, pi
> degrees(pi)
180.0
> from math import degrees as deg
> deg(pi)
180.0
3.6 Control statements:
With some functions at your fingertips, it is often nice to have some control statements as well. These statements are used to do things and automate tasks. All of these control statements can be nested.
3.6.1 if/elif/else statements
if statements, along with elif and else allow you to perform conditional tasks. These statements take the following form:
> if *condition*:
> *statement*
> elif *a different condition*:
> *another statement*
> else:
> *yet another statement*
Note that the statements are indented following a colon. Minimally, you can use an if statement by itself. The statement that follows will only be executed if it is true (or nonzero). If other conditions are necessary, you can use the elif statement. If some statement should be executed when all other conditions aren’t met. You can use the else statement. For example:
> age = 42
> if age < 21:
> print "go home kid!"
> elif 21<= age <= 41:
> print "come on in!"
> else:
> print "aren't you getting a little old for this?"
aren't you getting a little old for this?
3.6.2 for loops
for loops give you a little more power. Now you can repeat a task. Basically, for loops iterate over a list, sending each element (in the order within the list) to a name that you provide. Once the program does something with that element, it moves on to the next one. For example:
> other = [1, 2, 3, 4, 5]
> for each in other:
> print each
1
2
3
4
5
In the above example, you could have named each anything that you wanted to. Also, the list can be provided as above, or may be provided explicitly or through the range function. The range function generates a sequence, that is x elements long, beginning with zero:
> range(3)
[1, 2, 3]
You can also start and end over a specified interval at a specified step:
> range(0,4,1)
[0, 1, 2, 3]
> range(0,4,2)
[0, 2]
> range(1,4)
[1, 2, 3]
> range(1,4,2)
[1, 3]
So now you can also run a loop as follows:
> for i in range(3):
> print i
0
1
2
> for i in [3, 1, 4, 1, 5, 9]:
> print i
3
1
4
1
5
9
3.6.3 while loops
while statements are similar to for statements in that they perform looped operations:
> while(condition is true):
> do something
The difference between them is that a while statement will continue to run until a condition is not true (or is equivalent to 0). So be careful using these, they can run forever if your code never satisfies the condition. Here’s an example:
> from math import e, factorial
> e1 = 1.
> x = 1
> while(e - ex1 > 0.0001):
> e1 += 1./factorial(x)
> x += 1
> print e1, " is approximately ", e
3.7 Functions
Functions are one of the most useful parts of any programming language. In addition to using functions that are found in one of python’s many built-in and contributed libraries, you can write your own functions. To do so you need to do the following:
> def name_of_function(variables):
> calculations to be performed
> return something
For instance if you wanted to calculate the area of a circle for a list of values, you could do the following:
> def area_of_circle(r):
> A = math.pi * r**2
> return A
or more easily: > def area_of_circle(r): > return math.pi * r**2
Now you can manipulate some data:
> import math
> radii = [1, 2, 3, 4, 5]
> for radius in radii:
> print area_of_circle(radius)
3.14
6.28
9.42
12.70
15.84
3.8 File I/O
There are many ways to read and write files. Below are a few methods that vary with their ease of use. I would recommend using facilities in the csv library since most data are in this format and because this data format is compatible with most all spreadsheet and statistical software packages.
Here are two methods for reading files:
f = open('human_dims.csv','r')
data = f.readlines()
header = data.pop(0)
for lines in range(len(data)):
data[lines] = data[lines].split(',')
for i in range(len(data)):
for j in range(len(data[i])):
data[i][j] = float(data[i][j])
or
import csv
data = []
for row in csv.reader(open('/Users/msears_bmc/Desktop/human_dims.csv','rb')):
data.append(row)
header = data[0]
for i in range(len(data)):
for j in range(len(data[i]):
data[i][j] = float(data[i][j])
Note that there are three modes when opening a file\: read, write, and append. Be careful with these, they do different things. r designates simply reading from a file. No harm done here. w designates writing mode, and will overwrite any file from scratch. So if you use it, mean it or else you will lose any previously saved data. If you want to add more data to a file use a, which will designate the append mode. Appending simply adds to the end of a new or existing file.
Now, to write a file
of = csv.writer(open('/Users/msears_bmc/Desktop/human_dims2.csv','wb'))
of.writerow(header)
of.writerows(data)
Using zip Note what the zip function does:
> height, weight = zip(*data)
> new_data = zip(height,weight)
zip can pack or unpack data. If you have a list of lists, like you might read from a data file, you can use the zip(*name_of_list) command to unpack the data into a corresponding number of lists. Then after you have performed all of the operations that you want on your lists, you can zip them back into a format for writing them back to a file.
There, again, are several ways to write to files. You can use csv.writerows() to write new_data to a file, or you can open a file in write mode and f.write() to it. Note that the f.write mode requires that values are converted to a string before writing.
3.9 Summary
This is pretty much the basics of Python that you will need to get started with some basic models. We will add more features as we go along, but for most tasks you could get along without these features…but they will make your life much much easier.