CS 151: Lab 1

Title image Project 1
Spring 2020

Lab Exercise 1: Equipping yourself for the projects

The purpose of this lab time is to give you an introduction to the basic tools we will be using this semester. These tools include a terminal, a text editor, and the Python interpreter.

Labs and projects are tightly coupled. Each project is initiated with a set of lab exercises. In the projects, you will write code that expands on the code written in lab. For each project, you will be writing Python code and running it. The programs typically create images. You will be posting some of these images, along with a description of the project, on a Wiki page. You will then turn in your code by putting it in a special directory on one of the campus computer servers. Today's lab will allow you to practice each of these tasks.

We'll be going through a lot of little things today. Here are some short tutorial videos if you need to revisit any of them as you start your project.


Tasks

  1. Introduction to the Terminal

    A terminal is a text-based method of using your computer that is much more powerful than using the restricted point and click interface. To start a terminal, open the Terminal application. It is located in the Applications::Utilities folder.

    In a terminal, you can type commands that will let you manipulate files, execute programs, and open documents. Anything you can do in the Finder, you can do in a terminal (the reverse is not true).

    When working in a terminal, the current directory is called your working directory. A terminal will usually start in the home directory of your account.

    In a terminal we often need to specify a file or directory on the hard drive. The complete description of where a directory or file on a computer is located is called its path.

    Directories in a path are separated by a forward slash /. The topmost directory on the filesystem is indicated by a single slash. The directory tree for your computer is all relative to the top level directory. In other words, starting with a /, you can type the complete path to any file on your computer. For example, the following is the path to my home directory.

    /Users/bmaxwell

    Most of the time, however, you will be specifying paths relative to your current directory. Any path that starts without a slash is relative to your current working directory. Note that paths are case-sensitive, so be sure to use proper capitalization.

    You will use paths, and filenames to change directories, list the contents of directories, and run Python programs.

    Some important terminal commands are the following. We'll walk through how to use them together in lab.

    • ls - with no argument, ls lists the files in the current directory. If you put a path after the ls command, it will list the contents of the specified path.
    • cd <directory> - change directory. If you use the command with no arguments, it changes the directory back to your top-level home directory. The current directory is specified as . and the parent directory of the current working directory is specified using ..

      Example cd commands
      cd Set the current directory to your home directory
      cd ~ Set the current directory to your home directory. (The ~ character is shorthand for your home directory.)
      cd .. Move up to the parent directory of the current working directory
      cd ../../    Move up to the parent of the parent of the current working directory.
      cd blah     Move into the sub-directory blah
      cd /Volumes/Courses/CS151/  Move to the directory give by the absolute path (starts with /).
      cd - Move to your last working directory

    • mv <from> <to> - move a file, including just renaming it in the current directory. The mv command will remove the file in the old location after copying it to the new location.
    • cp <from> <to> - copy a file to a new location or name
    • rm <filename> - remove the file (will not remove a directory). Not that this is not the same as dragging a file to the trash. Once the filed as been removed, it is gone for good.
    • rm -r <directory> - remove the directory and all the files and subdirectories in it

    Some useful terminal properties are the following.

    • Wildcard characters: the star character * is a wildcard character. If you want to see all the files in a directory that start with A, you can type:

      ls A*

      A possibly bad thing to do is to type rm *

    • Tab completion: when you have typed part of the name of a file or program, pressing the tab key will complete the filename as far as possible while the choice is unique. For example, if you have only one file that starts with the letter b, then typing b and then the tab key will complete the filename.

      If you have two or more files that start with b, tab completion will beep at you. If you press tab again, then the terminal will show you the options (all the files that start with b).

    • Hitting return - you don't have to be at the end of the line to press return. If you go back and edit something in a terminal command, youcan press return and execute the whole line no matter where the cursor is located. Try it.
    • Control keys - holding down the control key and pressing another key lets you execute a number of different useful commands. Learning these will make you faster that using arrow keys or the mouse.

      CommandAction
      cntl-amove the cursor to the start of the line
      cntl-bmove the curse back one position
      cntl-ckill the current process running in the terminal
      cntl-ddelete the character under the cursor.
      cntl-emove the cursor to the end of the current line
      cntl-fmove the cursor forward one position
      cntl-kdelete everything on the current line to the right of the cursor
      cntl-lclear the terminal screen.
      cntl-nmove forward in the terminal history
      cntl-pmove backward in the terminal history
      cntl-zfreeze the current process running in a terminal. You can put it in the background by typing bg or put it in the foreground by typing fg.

    Some useful (but not as common) terminal commands are the following.

    • pwd - tells you the complete pathname of the current directory
    • less <filename> - scroll through a file
    • cat <filename> - send the file to standard output
    • echo "a string" write the text within the string to standard output
    • touch <filename> touch either updates the modification date on a file or creates an empty file if the named file does not exist. This can be useful in various situations, like when you are learning to create, rename, and delete files using a terminal.

  2. Introduction to the file servers

    A fileserver is a central file system you can access from any computer. It's like having a virtual USB key you can plug into a computer to store your files. Colby maintains two different fileservers we use in this course. One (the Personal server) is for you to store the code you are working on. The other (Courses) is for you to turn in code. We will talk about the Courses directory later in the lab. For now, let's focus on where you should keep code that is work in progress.

    You can mount the Colby fileserver root directory by going to the Finder and typing cmd-K, or selecting 'Connect To Server...' from the Go menu. It will bring up a dialog box, into which you want to enter the following.

      Macs (CS Computer Lab):   smb://filer.colby.edu
      Windows: \\filer.colby.edu

    This system is backed up up regularly, and you can access it from any computer on the Colby network. We strongly suggest you store all of your work for this course into your personal directory. You can, in fact, work directly from your personal directory. Let's practice doing that for the first project.

    Project Prep:

    1. Mount your personal directory (Cmd-K, then smb://filer.colby.edu).
    2. In the terminal, navigate to it. Type cd followed by the path to the directory. E.g. for Bruce, it may look like this:

      cd /Volumes/Personal/bmaxwell

      Or, use a shortcut. If you type cd in the terminal, then drag the icon for your directory onto the terminal window, then the path to it will automatically be pasted.

    3. Make a directory (in your personal folder) named project1. You can do this using the Finder, or you can type mkdir project1 into the terminal.


  3. Introduction to text editing

    Text editors are the workhorse programs for writing code. You don't want fancy fonts or WYSIWYG layouts, you just want to see lines of text, preferably with syntax highlighting, which means that special words in a language are highlighted to make it easer to read the code. There are many editors to choose from.

    In lab, I will be using TextWrangler. It is a free text editor for the Mac and it has all the features I need for writing programs. If you would like to install it on your personal computer, go to the TextWrangler web site and follow their instructions (which will tell you that TextWrangler itself is not what they want you to install - you should install BBedit instead. We are sticking with TextWrangler in lab because we have a working version and like it.).

    Creating Your First Python Program:

    1. Open TextWrangler
    2. You may want to set some preferences.

      For example, it can be useful to display line numbers. This will help later, when you encounter error messages that tell you where an error is by supplying the file's name and the line's number.

    3. Create a new file (Cmd-N). Save it as smart.py in your project1 directory.
    4. Put in the line:

      print('You are smart')

    5. Then save the file (Cmd-S).
    6. Instruct Python to execute (run) the program. In the terminal type

      python3 smart.py

      Congratulations, you just ran your first Python program. (Python humor)

      Note that the above command works only if the current working directory is the one that contains the file smart.py. So, one thing you need to do when working on a project is to ensure that your Terminal is in the right directory. Think of it as making sure TextWrangler and Terminal agree about where the programs are. You can always use ls to see the contexts of the current directory or pwd to get the path of the current directory.

      In general, you run Python programs by typing

      python3 <filename>

    For your information

    Here are some other text editors you should know about:

    • Atom - a simple and free code editor that is available for MacOS, Windows, and Linux.
    • Sublime Text - a non-free code editor (but free if you can put up with ads) available for MacOS and Windows.
    • Notepad++ - a free and open source text editor for Windows.
    • Visual Studio Code a free and open source code editor developed by Microsoft, available for MacOS, Windows, and Linux.
    • Bracket a free and open source code editor developed by Adobe, available for MacOS, Windows, and Linux.
    • nano/pico - nano (or pico on some systems) is a very simple text editor that works in a terminal. All of the commands use the control key and are listed at the bottom of the screen. To open up a file, just type the name of the editor followed by the name of the file. If the file does not exist nano creates the file.
    • BBEdit - BBEdit is an upscale version of TextWrangler designed for writing code and html (web pages). Colby has a set of licenses for it, and it is installed on the lab computers. It has a few more features than TextWrangler, but will only work on the lab computers.
    • emacs - emacs is a text editor that has been used heavily by computer scientists for almost 40 years. It has many powerful capabilities, and the key commands in emacs are used in many other places (like TextWrangler). emacs is the battery-powered swiss-army knife with optional nuclear reactor of the editor world (emacs humor).

      If you open emacs, the opening screen tells you how to access a tutorial. The most important thing to know is how to save and get out. To save, hold the control key down and type x then s (C-x C-s). It will ask you for a filename (and give you a default if you opened a file) and then save it. To exit, hold down the control key and type x then c (C-x C-c).

    • JEdit - JEdit is very simlar to TextWrangler, and you can download it for free and run it on any operating system. Many students use it since it runs on Windows. It is slightly more complex than TextWrangler.
    • XCode - XCode is a powerful integrated development environment for Mac OSX, but you can also use it just for its editor, which is pretty decent.

  4. Introduction to the Python turtle

    Python is a simple yet powerful interpreted language for making computers do stuff. Many people have written modules for Python that do some sophisticated things. One of those modules is called turtle and implements turtle graphics (e.g. forward, left, right, pen down, and pen up).

    We can make the turtle move forwards, backwards, turn left, turn right, and pick up or put down the pen using the following commands.

    • forward(x) - move forward x pixels
    • backward(x) - move backward x pixels
    • left(a) - turn left a degrees
    • right(a) - turn right a degrees
    • up() - pick up the pen (don't draw when the turtle moves)
    • down() - put the pen down (draw when the turtle moves)

    More complete documentation is available on the Python documentation site.

    Writing Your First Turtle Program

    1. Create a new code file

      In TextWrangler, select New from the file menu.

    2. Always put the proper header at the top of each code file.

      Type your name, a date, and the course and project in a comment at the top of the file. Every Python file you ever write should start with these three lines.

    3. Import the turtle package

      On the first line of your code file, put the instruction:

      from turtle import *

      That will import all of the turtle commands (i.e. it will give you the ability to direct the turtle to draw for you.)

    4. Write the code to wait for user input when done drawing

      On the last line, put the instruction:

      input('Press Enter to continue')

      That will keep the turtle window open until you press return in the terminal. When you are finished, save a copy of your Python file to your directory on the Personal server.

    5. Save your file

      Save the file in your project1 directory on Personal. Call it simple_turtle.py because it is your first turtle program. Notice that the filename ends in with the .py extension, which indicates the file contains Python code.

    6. Have the turtle draw a square

      Using the right and forward turtle functions (commands), draw a square. Place one command on each line, and put them in between the import and input commands.

      forward(100)
      right(90)
      forward(100)
      right(90)
      forward(100)
      right(90)
      forward(100)
      right(90)
    7. Test your code

      Run the program from the terminal using python3 simple_turtle.py. What does it draw?

    8. Define a function to draw the square
      1. A function is a named block of code. You can execute the code by using the function's name along with any arguments the function requires.
      2. To define a function, start with the keyword def followed by the name of the function. A pair of parentheses after the function's name can include parameters to the function. Finally, the function definition ends with a colon, which is how Python defines the start of a block of code. Type the following example.

        def square():

        The name of this function is square and it has no parameters. After the function definition, we can write the code that belongs to the function. Any code inside the function must be tabbed in relative to the function definition. Move the code for drawing a square inside the function. You can shift the whole block of code right at once by using the Text::Shift Right menu command.

        If you were to run your program, it would do nothing because your code only defines the function, it does not execute it.

      3. Call the function

        After the function definition is done, call the function so that it executes. To call a function, use the name of the function followed by parentheses enclosing any arguments. In this case, use the following code.

        square()

        Test your code.

        After calling the square function, add a right turn and call it again. What happened?

      4. Add a parameter to the function

        As written, the function can draw a square of only one size. To make the function more flexible, add a parameter to the function definition. Put a variable name, e.g. size inside the parentheses of the function definition.

        Next, replace all instances of 100 in the turtle code (just the calls to forward) with size.

        Finally, in the two calls to the square() function, put 100 inside the parentheses for the first call and 50 inside the parentheses of the second call. These are arguments.

        Run your code, what happened?


  5. Introduction to the Wiki

    Colby Wiki - a Wiki is a convenient way to put content up on the web quickly and easily.

    Log in to the wiki. Click on the "Create your personal space" link one at a time (if too many people do this at once it crashes the wiki).

    For each project, you will create a new page in your wiki space. You can create a new page in your space by pressing the "Create" button on the top menu bar or clicking on the "Create Child Page" link in the lower left of the left side bar.

    You can edit any existing page in your space by navigating to that page and then clicking the Edit link in the upper right.

    Project Prep:

    1. Make a page for Project 1
      1. Press the "Create" button. In the dialog window, choose the "CS 151 Project Template" and press the Next button.
      2. Replace the "New Page" title with "[[Your Name]]'s CS151 Project 1" so that the page content is clear from the title.
      3. In the template replace $studentName with your first and last name, and $projectNumber with 1.
      4. Now save your page; it is a good idea to save often.
    2. Link your Project 1 page to your wiki Home page.

      After saving your page, it will show up in the list of child pages in the side bar. To make it easier to find this page again, make a link to it from your wiki home page.

      1. Go to your wiki home page (select Personal Space from the person-menu in the upper right).
      2. Press the Edit link and then put your cursor where you want to put the link.
      3. Press the link button (it looks like a chain) and search your space for the page you want to link.
      4. Click the Save button to save the changes and exit edit mode.
    3. Capture part of your screen as an image.

      For all of your wiki project reports, you will need to include pictures of the images you create with your programs. Since this project is an introduction to writing Python turtle code, the first required picture is of the tools you need to write and run the code. Since you have already drawn a square, let's include it as well.

      1. Set up your screen: Run your simple_turtle.py program and leave the image up. Then arrange the terminal, the image, and TextWrangler so they are all visible (and make sure TextWrangler has simple_turtle.py displayed).
      2. Take a picture of these three things by pressing Command-Shift-4. A cursor will pop up. Click and drag a box around the hexagon, TextWrangler, and the Terminal. The computer will take a picture of it and place the picture on your desktop.
    4. Add the picture to your project 1 page.
      1. Navigate to your project page and click Edit.
      2. Add text to your Task 1 saying "These are the tools we use."
      3. Place the image in the page. To insert an image use the mountain button (may be under the + menu) and upload the image from your Desktop. When you upload the image, you have the option of controlling its size. Making your images smaller can make your report more readable. The user can still see them full size by clicking on the image.
    5. Label your project 1 wiki page page.

      A label is not a title. A label is a tag that lets us quickly find all of the wiki reports for a given project. Each assignment will specify a label, which we will use to find your pages so we can show off your work and so we can grade it.

      1. Click on the pencil icon on the lower right of your project page.
      2. In the labels dialog, enter the label cs151s20project1 and click Add.
      3. Close the dialog and make sure the label appears at the bottom of the page.
    6. Save your page, then sit back and think about how much you have already accomplished.

    For your information

    If you ever need to remove a page, go to that page and select "Remove" from the "Tools" menu in the upper right.

    Remember to save your wiki page before navigating away from it. The wiki won't detect it and remind you.


  6. How to turn in code

    You will turn in your code by putting it in a directory in the Courses server. On the Courses server, you should have access to a directory called CS151, within that a directory with your user name, and within that a directory called Private. Files that you put into the Private directory you can edit, read, and write, and the professor can edit, read, and write, but no one else. To hand in your code and other materials, you will create a new directory, such as project1, inside your Private directory and then copy your code into the project directory for that week.

    You can mount the Colby Courses fileserver by going to the Finder and typing cmd-K, or selecting 'Connect To Server...' from the Go menu. It will bring up a dialog box, into which you want to enter the following.

      Macs (CS Computer Lab):   smb://filer.colby.edu
      Windows: \\filer.colby.edu

    Select Courses from the set of choices. Then, in the resulting finder window, click on the CS151 directory, and then your hand-in directory (it will have your username as its name).

    Project Prep

    Within your hand-in directory there should be a Private folder. Within the Private folder there is the folder Projects. Hand in your projects in the Projects directory.

    Practice turning in your code by copying your entire project1 directory from your Personal server to the appropriate location on the Courses server (Bruce's would be /Private/Projects/bmaxwell_P01). The easiest way to do this is to drag and drop the folder from one Finder window open to Personal to another Finder window open to Courses.


When you are done with the lab exercises, you may start on the rest of the project.