In Class: Week 1, Thursday


Run update21 to download class files. Then cd into this week's directory.
$ update21                           # download updates
$ cd                                 # go to home directory
$ cd cs21                            # go to the cs21 directory
$ pwd	          
  /home/your_user_name/cs21

$ cd inclass                           # go to the inclass directory 
$ pwd		
  /home/your_user_name/cs21/inclass

$ cd w01-intro                          # go to this week's directory
$ pwd           
  /home/your_user_name/cs21/inclass/w01-intro

You should see three files in the directory

$ ls
WHAT_I_EXPECT_FROM_YOU	add.py	calcTax.py  firstProg.py  loop.py  welcome.py

  1. We are going to start by looking at the firstProg.py program together, so go ahead and open it in vim:
    $ vim firstProg.py  
    
    This is the command to run the program in the python interpreter:
    $ python firstProg.py
    

  2. Try modifying the firstProg.py in vim to print out a different string, and run it. Note than Python is white-space sensitive. That is, everything that is indented the same (lined up on the left side) is considered a group of code that runs together. Incorrect indentation confuses Python or leads to improper execution of your program. A convention is to use spacing of 2 or 4 spaces per level.

  3. Next we will look at add.py. This program follows the general pattern that all (most) programs follow:
    1. input phase: get data values for program variables
    2. compute phase: do something with the program's data (some operations on variables and values)
    3. output phase: display the results to the user

  4. Time permitting, try out the following exercise: create a program in calcTax.py that asks the user for the cost of the item. Then, proceed to calculate a 6% sales tax and output the total item cost, including cost.

  5. Finally, we will look at loop.py. This is an example of a program that uses a for loop. A loop construct tells the python interpreter to repeat a set of instructions some number of times.

Running Python Programs

You can run your python program in the python interpreter two different ways (we will use the first way most of the time):
  1. Have the interpreter run your program to completion:
    $ python firstProg.py
      Hello There
    $
    
  2. Run the interpreter in interactive mode on your program (the python interpreter will continue to run after running your program, and you can enter new python commands at the prompt >>>:
    $ python -i firstProg.py
      Hello there
      >>> print "I love computer science!"
      I love computer science!
      >>> print 13 + 7 + 11
      31
      >>>
    
To exit the python interpreter hold down the control and the D keys together (CNTL-D)

You can also just start the python interpreter in interactive mode without giving it a python code file to run:

  $ python
  >>>