Computer Science 15-112, Spring 2013
Class Notes:  Getting Started in 15-112


  1. Logistics and Preliminaries
  2. Running Python
  3. Hello World in Python
  4. Python Comments
  5. Errors
    1. Syntax Errors (Compile-Time Errors)
    2. Runtime Errors ("Crash")
    3. Logical Errors (Compiles and Runs, but is Wrong!)
  6. Basic Console Output
  7. Basic Console Input
  8. Importing Modules
  9. The vim editor
  10. The Linux Shell
  11. Getting Started with Variables
  12. Getting Started with Writing Functions

Getting Started in 15-112

  1. Logistics and Preliminaries
    1. 15-112 vs 15-110 (Are you in the right course?) (Really?)
    2. Programming vs Computer Science
    3. Course Objectives (eg, student project gallery)
    4. Waitlist policy
    5. My CMU web page (http://www.cs.cmu.edu/~koz/)
    6. Course web site (http://www.cs.cmu.edu/~112) and backup site here.
    7. Course Policies / Syllabus
    8. Your well-being and happiness
    9. Course mailing list + archives
           https://lists.andrew.cmu.edu/mailman/private/15-112/2013/date.html
    10. Course schedule
       
  2. Running Python
    1. via TryPython or repl.it
      1. Simply go to:  http://www.trypython.org/
      2. Or go to:  http://repl.it (and choose Python, of course)
    2. Skulpt + HTML5/Canvas:  A hint of things to come...
    3. via Windows/Mac Python install
      1. Install Python
        from: http://www.python.org/download/releases/2.7.2/
        Note: probably already installed on Macs!
        Note: be sure to use appropriate 32-bit or 64-bit install!
      2. Add the python directory to your system path (also probably not required on Macs, here are some instructions for Windows):
        1. First, you have to find where Python installed itself.  You might try to look for it in one of these locations:
          • c:\program files\python27
          • c:\program files (x86)\python27
          • c:\python27
        2. Once you found it, you have to tell the Command Shell where to find it (silly, but true), as such:
          1. Go to Start / Control Panel / System / Advanced System Settings / Environment Variables
          2. On bottom half of window (System Variables), select Path and click Edit button
          3. In the variable value textbox, go to the end and type a semicolon, then...
          4. Type the path to the directory where you found the Python install (back in step 1 above)
          5. Click ok as needed (three times, probably) to finish the procedure.
          6. Changes will be visible the next time you open a Command Prompt (or shell or terminal)
      3. Run a Command Prompt or Command Shell or Terminal
      4. Type   python   or type    python myscript.py
        (If it says that python is not recognized or found, it means you did not set your path correctly above.  Please see a course staff member for assistance!)
      5. To run IDLE (Python GUI):  either run IDLE from Start menu, or type:  python -m idlelib.idle
      6. Also suggested:  Install Komodo Edit (http://www.activestate.com/komodo-edit) (Note: Komodo Edit is free, Komodo IDE is not.  Use Komodo Edit.)
        1. How to run Python in Komodo Edit
          1. Mac OSX:
            1. go to Toolbox -> Add -> New Command...
            2. in the top field enter the name 'Run Python file'
            3. in the 'Command' field enter this text:   %(python) -u %F
            4. click Ok.
          2. Windows:
            1. go to Toolbox -> Add -> New Command...
            2. in the top field enter the name 'Run Python file'
            3. in the 'Command' field enter this text:  "%(python)" -u "%F"
            4. click Ok.
             
        2. Even better, how to save-and-run Python in Komodo Edit
          This solves the problem that Komodo Edit will run the last-saved version, not the current version, of your file.
          1. First add the Run-Python command from above
          2. Be sure you can see the Run-Python command in the Toolbox (probably on the right-hand side)
          3. Load a Python file and modify it but don't save it
          4. Select Tools/Macros/StartRecording
          5. Select File/Save
          6. Double-click on the Run-Python Command
          7. Select Tools/Macros/StopRecording
          8. Select Tools/Macros/SaveToToolbox, name your Macro Save-and-Run Python (or some such)
          9. Right-click on the Save-and-Run Python command in the toolbox, and select properties
          10. Select Key Binding, then click in New Key Sequence box, enter F5 or ctrl-2 or whatever you like, then select Add (to the right of the box) and then OK (at the bottom).
          11. That's it!  Now when you press F5 (or whatever binding you used), you'll save-and-run the Python file.
             
    4. via GHC Cluster
      1. Physically go to a GHC cluster (say, 5201 or 5205)
      2. Login using your andrew id and password
      3. Run SystemTools/Terminal
      4. Type   python   or type    python myscript.py
      5. To run IDLE (Python GUI):  in an xterm, type:  python -m idlelib.idle &
    5. via ssh
      1. Install ssh client (recommended:  PuTTY (for ssh) and SSH Tectia Client (for file transfer) from https://my.cmu.edu/, go to Computing, then Download Software)
        Note: probably already installed on Macs!
      2. Run ssh client connected to linux.andrew.cmu.edu
        On Windows, run PuTTY or "SSH Tectia - Terminal" from Start menu, select "Quick Connect", enter linux.andrew.cmu.edu
        On Mac/Linux, in a terminal just type: 
        ssh andrewid@linux.andrew.cmu.edu
        (of course, replace andrewid with your actual andrew id).
      3. Or run ssh client connected to ghcN.ghc.andrew.cmu.edu
        1. Choose N from 10 to 80 (to load balance, choose randomly, maybe add one each time)
      4. Type   python   or type    python myscript.py
         
  3. Hello World in Python
    1. Interactive
      1. in python, type:
             print "Hello World!"
    2. From a script (via ssh)
      1. Do this outside of Python, running from an ssh shell (that's the whole point here)
      2. create the script (type this, exactly (maybe copy-paste it), into the ssh shell):
             echo 'print "Hello World!"' > myscript.py
      3. Then type this into the ssh shell:
             python myscript.py
         
  4. Python Comments 
    print "Hello World!" # This is a comment
    # print "What will this line do?"

  5. Errors
    1. Syntax Errors (Compile-Time Errors)
      print "Uh oh! # ERROR!  missing close-quote
      
      Python output:
      SyntaxError: EOL while scanning string literal
    2. Runtime Errors ("Crash")
      print 1/0 # ERROR!  Division by zero!
      Python output:
      ZeroDivisionError: integer division or modulo by zero
    3. Logical Errors (Compiles and Runs, but is Wrong!)
      print "2+2=5" # ERROR!  Untrue!!!
      Python output:
      2+2=5
  6. Basic Console Output
    1. Basic Print Statement
      print "Carpe"
      print "diem"

       
    2. Print with Comma
      print "Carpe",
      print "diem"

       
    3. Print Multiple Items
      print "Carpe", "diem"

      Another Example:
      # Compute the hypotenuse of a right triangle
      a = 3
      b = 4
      c = ((a**2) + (b**2))**0.5
      print "side a =", a
      print "side b =", b
      print "hypotenuse c =", c
       
  7. Basic Console Input
    1. String with raw_input()
      name = raw_input("Enter your name: ")
      print "Your name is:", name

    2. Number with raw_input() (error!)
      x = raw_input("Enter a number: ")
      print "One half of", x, "=", x/2 # Error!


    3. Number with raw_input() and int()
      x = int(raw_input("Enter a number: "))
      print "One half of", x, "=", x/2


    4. Strings and Numbers with input()
      x = input("Try this with a string and then a number: ") # input() is not recommended!
      print 2*x
       
  8. Importing Modules

    Fails:
    print math.sqrt(5)
    Python output:
    NameError: name 'math' is not defined
    Works:
    import math
    print math.sqrt(5)
    Python output:
    2.2360679775
  9. The vim editor
    1. After creating myscript.py in the previous step, type this into the ssh shell:
           vim myscript.py
    2. You start vim in command mode (so you cannot enter text yet!)
    3. Some vim commands:
      Key Command
      h or Left Left
      l or space or Right Right
      k or Up Up
      j or Down Down
      0 Start of line
      $ End of line
      nG or :n Go to line number n
      i Insert at cursor
      a Insert (append) after cursor
      I Insert at beginning of line
      A Insert (Append) at end of line
      ESC Exit insert mode (switch back to command mode)
      x Delete current cursor position
      dd Delete current line
      ndd Delete n lines
      p Paste ("push" last text cut/deleted) at the cursor
      u Undo last change
      ctrl-r Redo
      /text Search for text
      n Search for next occurrence of text
      :w Write file
      :w! Overwrite file (ignoring warnings)
      :wq Save (if necessary) and quit
      :q Quit if saved (or warn if unsaved)
      :q! Quit without saving (be careful!)
    4. Printable list of vim commands:  vimCommands.doc
    5. More vim commands (Google vim tutorials, pick your favorite!)
      Also, try:  /usr/bin/vimtutor  (or just vimtutor)
    6. Your .vimrc file
      1. In ssh shell, type this (maybe copy-paste it to be sure to exactly match):
             vim ~/.vimrc
      2. Then, enter input (or view) mode (say, by the command A)
      3. Then, copy these lines into that file:
        set tabstop=4
        set shiftwidth=4
        set expandtab
        set autoindent
        set number
        syntax on
      4. Finally, save the file and exit.  Changes take effect next time you run vim.
    7. Copy-pasting code (say, from the course website) into vim
      1. The problem:  vim will try to autoindent already-indented code, leading to a mess
      2. The solution:  first switch vim into paste mode, with this command:
            :set paste
        Then do the paste.  Then switch out of paste mode with this command:
           :set nopaste
        That’ll do it!  You can also try to add this to your .vimrc file:
           set pastetoggle=<F12>
        Then, when you press the F12 key, you should automatically switch between paste and nopaste modes.  Unfortunately, this did not work for me when ssh’ing via Tectia, but it did work in all other cases (including ssh’ing via Putty)

         
  10. The Linux Shell
    1. Some Linux shell commands (enough to get started):
      Command Description
      whoami Print login id of current user
      hostname Print name of current host (computer)
      users Print user names of all users on current host
      pwd Print present working directory (where am I?)
      cd dir Change directory to dir
      cd ~ Change directory to user's home directory (~)
      ls List files in the current directory
      ls -alst List files with lots of useful information
      ls dir List files in the directory dir
      mkdir dir Make a directory named dir
      rmdir dir Remove the directory named dir (must be empty)
      vim file Use vim to edit the given file
      cat file Print (concatenate) the file(s) to standard output
      more file Print the file, one page at a time
      cp file1 file2 Copy file1 to file2
      cp -r dir1 dir2 Copy (recursively) directory dir1 to dir2
      mv file1 file2 Move (rename) file1 to file2 (may be directories)
      rm file Remove the file
      man cmd Display the manual pages for cmd
      history Print recent history of shell commands
      up/down arrows Navigate history of shell commands (also ctrl-p/ctrl-n)
      cmd Run the command cmd
      eg: /afs/cs.cmu.edu/academic/class/15112-f11/bin/hello
      or: /usr/bin/vimtutor
      ./cmd Run the command cmd in the current directory
      ln -s cmd Make a symbolic link to cmd in the current directory
      alias name cmd Make an alias with the given name for the given command
      eg: alias hi /afs/cs.cmu.edu/academic/class/15112-f11/bin/hello
      alias List all aliases
      unalias name Remove the alias with the given name
      clear Clear the terminal screen
      date Display the current date and time
      finger user Print information about user (use Andrew id for user)
      ping machine Test a network connection to the given machine (ctrl-c to stop)
      exit Exit the shell (and logout if in a login shell)
      logout Logout of a login shell
    2. More Linux shell commands (Google Linux shell tutorials, pick your favorite!)
      That said, here's a nice one (among many):
      http://www.ee.surrey.ac.uk/Teaching/Unix/
    3. Your .cshrc file
      1. In ssh shell, type this (maybe copy-paste it to be sure to exactly match):
             vim ~/.cshrc
      2. Then, append these lines to the end of that file:
        set path = ($path ~/bin /afs/cs.cmu.edu/academic/class/15112-f12/bin)
        alias a alias
        a hi hello
        mesg n
      3. Finally, save the file and exit.  Changes take effect next time you login.
         
  11. Getting Started with Variables
     
    1. Define a variable and use it
      x = 3
      print x
    2. Same, but with a nicer UI
      x = 3
      print "x =", x
    3. Use a variable without defining it
      print "yikes =", yikes # ERROR! No such variable as yikes
    4. Assigning and re-assigning
      x = 3
      print "x =", x
      x = 4
      print "x =", x
    5. Using two variables
      x = 3
      y = 4
      print "x =", x
      print "y =", y
      print "x + y =", (x+y)
  12. Getting Started with Writing Functions
    1. See Notes on Getting Started with Writing Functions

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem