Other pages: Bio/Geo/CS250, MainModelingWiki
1. Python
Programming is an essential skill for any scientist, whether for creating complex simulations or simply for reformatting data files. In this course you will be introduced to a versatile, syntactically easy programming language called Python.Python is an all-purpose scripting language. Anything you can do in C, you can do in Python. The main differences are:
-
Python is easy to learn. Python has very intuitive grammar rules, and it does many computer-housekeeping tasks for you that other languages require you to do yourself. Notably, Python does all sorts of time-consuming memory-management tasks that C programmers spend hours a day fiddling with.
-
Python is an interpreted language. C programs are compiled into applications that you run by, say, doubl-clicking their icons on your desktop. Python programs are run inside of an interpreter program and may be a little slower than compiled programs.
We'll be learning Python so that (a) we'll all have a common programming vocabulary, and (b) so that you'll have a powerful but simple modeling tool which you can apply to any task.
1.1. Setting up
Another great thing about Python is that it's free and available for every platform (Mac, Windows, Linux, etc.) I encourage you to install Python on your own computer, or on whatever computer you use most often. For practice, please install Python on the Modeling-Lab computer you're using now.
First, open a new web-browser window and go to
http://www.python.org/. Bookmark this site: it's the best place to go for Python documentation and tutorials. To get Python, go to
http://www.python.org/download/. Click on and install Python 2.2.2. (Python 2.3a1 is being tested, so we'll stay away from it for now.)
If you're installing Python on a Macintosh, go to
http://www.cwi.nl/~jack/macpython.html and install Python 2.2.2. If your Mac is running Mac OS 10.2 (a.k.a. "Jaguar"), you already have Python installed. Just go to Terminal and type python.
1.2. UsingPython
1. Double-click on the icon for Python IDLE (the name for Python's interactive mode). 2. You shold see a window with this prompt: >>>. That means that you're in interactive mode and can run single-line commands, as you'll do below. 3. You can also open a window for writing longer (i.e., multi-line) programs. You'll do that in a bit.1.3. Programming 1: Arithmetic, variables, text output
1. At the >>> prompt, enter (that is, type and then hit return) this:-
8+8
2. Python gives you the answer. Like Mathematica, Python's interactive mode can act as a fancy calculator. This feature is useful for trying out short pieces of code.
3. Now enter this:
-
a=8
4. Enter a. What happens? Can you get Python to tell you what a+a equals, without asking explicitly for 8+8? Hint: Python is an exceedingly intuitive language, and the way to do it is probably what you think it is.
5. What's just happened? That is, what happens when you enter a=8? You've created a variable -- a place in the memory to store information, and you've filled it. You named the variable a, and the information you stored there is the integer 8. When you just enter the variable name, Python tells you what's stored there. When you use the variable name in an expression, Python evaluates the expression using the stored information.
6. Enter this:
-
b=a+a
What information is stored in b? Can you verify your answer?
7. Other kinds of information can be stored in variables. Enter this:
first_name="Hillary" last_name="Rodham"First, verify what's stored in each of the variables. Then see what happens when you add the two variables using a + sign, like before. Can you make the result look more like standard English?
8. Like many programming languages, Python lets you store different kinds of information (called types) in variables. Numerical types include integers (whole numbers, on many computers in the range -2147483648 - 2147483647), long integers (whole numbers of any size), floating-point numbers, and complex numbers. Non-numerical types include strings (sequences of characters, like "HillaryRodham"), lists, tuples, modules, classes, files, and any number of types defined by you, the programmer.
So, these are the types, and variables can refer to information (technically called objects) of these types. We'll go through each type's properties and uses when they come up. It's not something you'll probably have to memorize; you'll use them as you need them, and after a while you'll know them.
9. One more thing for this section. Enter:
print first_name+last_name
Now enter:
print "is my Senator."
Now enter:
-
print first_name+last_name+"is my Senator."
Finally, enter:
print first_name, last_name, "is my Senator."
Why the difference between the + and the comma? We'll go through that in the next session. For now, be happy that you now know the most basic, most useful method of output. It doesn't look like much in Python's interactive mode, but it's very powerful when used from within a program.
1.4. Programming 2: Text input and string type
In interactive mode, you've asked Python to do one task at a time: add two integers, print out an expression, assign an object to a variable. In a computer program, you write down many of these tasks and specify an order for their completion.
So, first we'll have to learn how to write the program without Python executing every line as we write it.
1. Click New window in the File pull-down menu. You'll be writing a program in this window, naming and saving it, and finally running it.
2. In this window, write this:
x = 5 print x**2
Now go to File:Save, and save as first.py (or something, as long as it ends with .py), on the Desktop.
Finally, run the program by going to Edit:Run script. The output should appear in the original "shell" window. What does x**y do?
(If you're running the Python that comes with Mac OS X, you do this stuff just a little bit differently. In Terminal, exit the Python interactive mode by pressing Crtl-d. You're back in the regular Terminal shell. Write your Python program in a text file in BBEdit or Text Edit. Be sure you save as plain text, not rich text. (The default for new documents in Text Edit is rich text. You have to change the preferences and open a second new document.) Also be sure the file name has the extension .py, not .txt. Then in Terminal use cd to go to the directory where your program is. For example, if you saved to Desktop, you might enter cd Desktop. remember, OS X is basically UNIX, so you should know your basic UNIX commands like cd, ls, and pwd. Finally, to run the program, enter python program_name.py)
3. Congrats: you've written and run a Python program. Now, before we proceed, something tricky. Modify your program to say this:
x = 5 print "5 squared equals " + x**2
You might incorrectly expect the output to read: 5 squared equals 25. Instead it complains that an object of type string can't be concatenated to an object of type integer. so what can you do? This:
x = 5 print "5 squared equals " + str(x**2)
Try running it and verify that it works. Here's what's happened: str() is like a function. It takes the numerical input in the parentheses and returns as output the string-type object that corresponds to the number.
Strings are surrounded by quotation marks. The string "5" is a different type of object from the integer 5, and Python won't understand if you use one when you mean to use the other.
Don't worry about memorizing this stuff. Just remember it for future reference. If you get an error complaining about concatenating objects of different types, remember this. And try this:
x = 5 print "5 squared equals",x**2,"."
The difference between the + and the comma is that the + tells Python to create an object by concatenating two strings (or adding two numbers). The comma jsut tells it to print the two objects next to each other, with a space in between.
4. You know about simple text output. What about input? Run this program:
number=input("Enter any number.")
a=number**0.5
print "The square-root of" , str(number) , "is" , a
Also run this program:
name=raw_input("What's your name?")
print "Is your name" , name , "?"
So, use raw_input for string input, and input for numbers -- integer, floating-point, or complex.
1.5. Flow control
1. As they've been structured so far, our programs are executed top to bottom with no repetition, and every line is executed. for example, run this program:
print 1 print 2 print 3 print 4 print 5 print 6 print 7 print 8 print 9 print 10
You can tell from the output exactly what happened during each step, and you can tell how the computer just started at the top and worked its way down. (Note: this is a great debugging trick. If you're trying to find an error in your program, insert a few print some-number statements and see which ones are executed and which ones are skipped over because of a flow-control mistake.)
But most programs you write will require more sophisticated behavior.
2. First, conditoinals. Enter this:
a = 3
b = 4
if a > b:
print a, "is greater than", b
else:
print b, "is greater than", a
(Make sure that you indent where I've indented, and that both indentations consist of the same number of spaces or tabs. Python is unusual among programming languages in that indentations are important. Most languages use brackets or words like begin and end to set off blocks of code. Python uses indentations for this, so be careful that your indentations are precise and consistent.)
You now know how to make a program branch. Try this:
a = "BRYN"
b = "bryn"
if a == b:
print "Python is case-insensitive."
else:
print "Case counts!"
Notice the double equal-sign, ==. Computer programs have to be able to distinguish tests of equality, like when we ask the computer to decide whether a and b refer to the same string, from assignments, like in a = "BRYN". also notice that Python is indeed case-sensitive.
You don't need the else statement. This:
variable = 25
another_variable = 5
if another_variable**2 == variable:
print "Yes!"
Conditionals are useful for keeping the computer from doing the impossible:
numerator = 8
denominator = 0
if denominator != 0:
print numerator / denominator
(What does != mean? What about !< and !>?)
3. Conditionals have this structure:
if SOME-TRUE/FALSE-TEST: ACTION-IF-TRUE else: ACTION-IF-FALSE
Note that the actions can also consist of any number of lines of code:
x_coord = 3.2
y_coord = -4.0
if x_coord > 0 and y_coord < 0:
print "The point is in Quadrant III."
answer = raw_input("Would you like to move the point to Quadrant I? (y/n)")
if answer == "y":
y_coord = y_coord * -1
print "Okay, done."
else:
print "Okay, the point has not changed."
else:
print "The point is not in Quadrant III."
Okay, that's a relatively complicated program. It has multi-line blocks of code, and one of those blocks includes its own conditional. Can you follow the order of execution? can you predict the computer's behavior? Notice how important the indentation is. Imagine the program looking like this:
x_coord = 3.2
y_coord = -4.0
if x_coord > 0 and y_coord < 0:
print "The point is in Quadrant III."
answer = raw_input("Would you like to move the point to Quadrant I? (y/n)")
if answer == "y":
y_coord = y_coord * -1
print "Okay, done."
else:
print "Okay, the point has not changed."
else:
print "The point is not in Quadrant III."
It's (a) unreadable, and (b) impossible or very difficult to tell how many lines are supposed to go with each if or else statement.
4. Now loops. Look back at this program:
print 1 print 2 print 3 print 4 print 5 print 6 print 7 print 8 print 9 print 10
Clearly, there's a better way to accomplish the task of printing these ten integers. Here are two ways:
First way, the while-loop:
a = 1 while a <= 10: print a a = a + 1Second way, the for-loop
for a in range (1,11): print a
Notice that range() is kind of tricky. To get the whole picture of range(), try this. The \t is how you represent a horizontal tab in a string.
print "range(5,9) \t" , range(5,9) print "range(9) \t" , range(9) print "range(-8) \t", range(-8) print "range(-4,-2) \t", range(-4,-2) print "range(9,5) \t", range(9,5)
Can you describe in words the behavior of range()? By the way, sequences of objects (like integers) enclosed in square brackets are themselves objects, of a type known in Python as a list. We'll go through lists next time.
2. Assignment (Due Jan. 29 at 1:00 pm)
Write a Python program that does the following:A. Ask the user whether she wants option 1 or option 2.
B. Execute the appropriate option:
-
Option 1
-
Ask the user to enter a positive integer.
-
If the user enters a negative integer, make it positive.
-
Calculate the factorial of the integer and output it in a sentence.
-
Option 2
-
Ask the user to enter a positive integer.
-
If the user enters a negative integer, make it positive.
-
Calculate 2 to the power of the inputted integer.
-
If the integer is 0, the answer should be 1.
-
Output the answer in a sentence.
Hint: this assignment is all about flow control. It might help you to draw out a diagram of the tasks involved -- a flow chart. Also, if you need help and don't have a reference book handy, there are lots of easy-to-use Python resources at www.python.org.
