=================================================== Math 311w-01 Laboratory 2: Introduction to Linux and Python Date: 2011-09-09 =================================================== Goals for today ---------------------------- - To show you a command-line interpreter for Python - To show you how to use a command-line interpreter interactively - To show you some basics of the python language - To show you how to write python script - To show you how to run a python script - To show you how to save your work to your PASS account ================================= Getting Started... ================================= Check to see if your HP workstation is turned on. If it is not on, please turn it on. Push the Linux button in the front of the Belkin box, if it isn't pressed. Wait for Redhat Linux to give you a login box. Find the menu at the bottom of the screen labeled "Session". Open it and select 'GNOME'. Login with your PSU user name and password. Welcome to Linux. Your computer will now show you a gui interface with a dock at the top. The main menu should be in the upper left hand corner, and looks like a person with a red fedora hat on. On the desktop is a folder labelled "PASS". This is a link to your university provided storage space. This is where you want to save your work at the end of this lab. The first thing we need to do is get out of this gui to a terminal that shows a command line. right-click-on-Desktop -> Open Terminal This will open up a "terminal window", and the program running inside the window is called a "shell". "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.) For more information see: http://en.wikipedia.org/wiki/Shell_%28computing%29 http://en.wikipedia.org/wiki/Unix_shell Welcome to the command line. In the terminal window, there should be a line of text something like "[tcr2@lxhammond316-211 ~]$" This is called a command prompt. It doesn't really matter what it says. 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), but also a little scary because of it's arcane and obscure syntax. Fortunately, only a few commands are important for us right now. pwd: Displays the path to the directory you're currently in. Immediately after login this will be your home directory. ls: list the contents of the current directory. Use 'ls -l' ('-l' = 'long') to get lots more detail. cd: Changes the current directory. You can either give it: - a relative path: 'cd subdirectory' - an absolute path: 'cd /data/group/subdirectory' - or use it on it's own to jump straight to your home man: used to find the manual pages about a command, like 'man ls' - unfortunately, man(ual) is itself confusing. - 'man man' will tell you more about man For more information about common commands, see http://www.math.psu.edu/treluga/311w/lab2/fwunixref.pdf http://www.math.psu.edu/treluga/311w/lab2/linuxReferenceCard.pdf In the terminal, type "ipython" and hit return. This tells the shell to run a different shell that understands the python programming language. Python is a 5th-generation programming language. 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. You can learn all about it at on the web, or in this pdf-book http://www.math.psu.edu/treluga/311w/lab2/thinkCSpython.pdf http://www.python.org/ Python is free. If you have a mac, it's already on your machine. If you have a PC, you might try burning the following CD and booting from it. http://www.personal.psu.edu/tcr2/Ubuntu-Live-9.10-scientific.iso For help about parts of python, like sets, see for example http://docs.python.org/release/2.4/lib/types-set.html =============================================== The Python Interpreter =============================================== # A line beginning with '#' is a comment, and is always ignored # You do not need to type in comment lines. ### First, the interpreter works like a common calculator. 2 + 2 4*3 2*3+1 2*(3+1) 2 + 2; # A command without a semicolon at the end prints out an output. # A command with a semicolon at the end prints nothing. x = 2 + 2; print x; print 3*x; # Variables are made up of letters and '_', and are used to # store results as you go. The 'print' command is a simple way # to display results. ### boolean algebra for propositional logic # Sometimes, it is convenient to assign more than one variable # at a time. p,q,r = True, False, False p q r # For each of the following, try to predict # the answer you will get before you press # return. p or ( q and r ) ( p or q ) and r p or q and r not ( q or p) ( not q ) or p not q or p ###### conditionals and loops # Indentation has meaning in python. # Indentation is used like parentheses to # nest complicated commands if 3 > 5 : print "3 is greater than 5" else: print "3 is not greater than 5" for x in [1,2,4,8,16]: print x, # This should have printed out all these numbers in one line. # The comma at the end of the print statement means not to add # a new-line at the end of each print. for x in range(-5,6): print x, abs(x) for p in [True, False]: for q in [True, False]: print p, q, p and not q y = [-4,-2,0,2,4] for i in range(-10,10): if i in y: print "%s is in y"%i else: print "%s is not in y"%i ## common object types in python a = [1,2,3]; type(a) # this is a list. A list is ordered, indexed, and mutable (can be changed) a[0]=4 b = set(a); type(b) # b is a set made from a list. A set is mutable, but not ordered or indexed b[0] # Since sets are not ordered, asking for b[0] returns an error c = tuple(b); type(c) # c is a tuple. Tuples are like lists, (ordered, and indexed) # but are IMMUTABLE (can not be changed) c[0] c[0]=-3 # We can access the elements with an index, but we can not change the elements, # so the last should return an error. x = set([1,2,3]) len(x) # "len" is a function that tells you the number of elements # in a container like a set, list, or tuple. y = set([1,2,3]) x == y y.add(5) len(y) y x == y x != y y.issubset(x) x.issubset(y) u = set(range(-3,5,2)) v = set(range(-5,1)) # what do you think u and v are? u v u.difference(v) v.difference(u) # You can do allot more with the interactive terminal, but # this has hopefully given you an idea of where to start. # You can learn more about anything in python with the help # command. help(u) # For now, we'll move on to something else. ====================================== Python Scripts ====================================== Typing in commands can get tedious, especially when you want to repeat something you already typed. The 'up-arrow' will show you old commands, but a more useful method is to store you commands in a script-file. Right-click-on-Desktop -> Create Document -> Empty File Enter "my_first_script.py" as the filename. (Or whatever. Just remember what you choose.) Double-click on the file. This will open your file in a text-editor. It will be empty at first. Type in the following. Be sure indent consistently, and in the same way (tab-key is probably best). ## start of script ## print "Hello, World" def AFunction(x): return abs(x) import random def NotAFunction(x): return random.choice([-1,1])*x def main(): for x in range(-3,3): print "=== x = %d ==="%x print " ## AFunction ##" for t in range(6): print "Trial %d"%t,x,AFunction(x) print "-----------" print " ## NotAFunction ##" for t in range(6): y = NotAFunction(x) print "Trial %d"%t,x,y,AFunction(y) main() ## end of script ## # what do you thing the output of this script will be? ================================ Running your new python script ================================ Save your file. Open a new terminal window (right-click on the desktop). $ cd Desktop $ ls # You should see a list of file names including your new text file, # "my_first_script.py" $ cat my_first_script.py # this will list the contents of the file $ python my_first_script.py # this command runs your script. Inspect the output, and see if it # does what you expected. If you entered part of the # script incorrectly, you may see an error message. "Debug" # your script by trying to find where things are wrong and # fixing them. That's it. Now you know the basics of how to write a python program. No limits from here on out. One last thing. ============================================== Saving your work for another day ============================================== $ cd ~/Desktop/ $ pwd # to check that you are in your machine's Desktop directory $ cp my_first_scripy.py PASS/ # that's it. Now, your file has been copied to your PASS directory. # Next time you need it, look there. # WARNING: IF YOU HAVEN'T COPIED ALL YOUR WORK SOMEPLACE SAFE BEFORE YOU # LOG OUT, YOU MAY LOSE IT. Now, close out your session.... System -> Log Out