Introduction

This tutorial will cover the basics of working in the Unix environment and a small Python tutorial. It assumes you have a working version of Python 2.5-2.7 (if you do not, the CoC machines come with them preinstalled) and is working in an Unix environment. It is required that you work in python 2.5-2.7 for the projects in this class, but it is not required that you work in a Unix environment.

You can download all of the files associated with this tutorial (including this description) from the attached files.

Submission

To get you familiarized with the automatic grading system, we will ask you to submit answers for problems 1 (buyLotsOfFruitfunction) and 2 (shopSmartfunction). This is a good thing: learning the basics of python now will save you many headaches later in the course. Keep in mind that this project will not be graded and is only intended to be used as a helper.

Please submit this tutorial as a ZIP or RAR archive named p0 as an attachement to this assignment. You should only submit the files that you modify (byLotsOfFruit and shopSmart).

The problems for submission are copied here for your convenience, but it may still be beneficial to work through the rest of the tutorial below.

Problem 1 (for submission): Add a buyLotsOfFruit(orderList) function to buyLotsOfFruit.pywhich takes a list of (fruit,pound) tuples and returns the cost of your list. If there is some fruit in the list which doesn't appear in fruitPrices it should print an error message and return None (which is like nil in Scheme). Please do not change the fruitPrices variable.

Test Case:We will check your code by testing that the script correctly outputs

Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25

Problem 2 (for submission): Fill in the function shopSmart(orders,shops) in shopSmart.py, which takes an orderList (like the kind passed in to FruitShop.getPriceOfOrder) and a list of FruitShopand returns the FruitShop where your order costs the least amount in total. Don't change the file name or variable names, please. Note that we will provide the shop.py implementation as a "support" file, so you don't need to submit yours.

Test Case:We will check that, with the following variable definitions:

Unix Basics

Here are basic commands to navigate UNIX and edit files.

File/Directory Manipulation

When you open a terminal window, you're placed at a command prompt.

kurtis%

The prompt shows your username, the host you are logged onto, and your current location in the directory structure (your path). The tilde character is shorthand for your home directory. To make a directory, use themkdircommand. Usecdto change to that directory:

The Python files used in this tutorial should be placed in this directory. To copy them to your directory, use thecpcommand. The*is a useful way to specify multiple files in a given directory;*.pyrefers to all filenames that end have the.pyending. Note that.is shorthand for the current directory. Uselsto see a listing of the contents of a directory. Some other useful Unix commands:

rm removes (deletes) a file

mv moves a file (ie. cut/paste instead of copy/paste)

man displays documentation for a command

pwd prints your current path

xterm opens a new terminal window

mozilla opens a web browser

Press "Ctrl-c" to kill a running process

Append & to a command to run it in the background

fg brings a program running in the background to the foreground

The Emacs text editor

Emacs is a customizable text editor which has some nice features specifically tailored for programmers. However, you can use any other text editor that you may prefer (such asvi,pico, orjoeon Unix; or Notepad on Windows; or TextWrangler on Macs; andmany more). To run Emacs, typeemacsat a command prompt:

[cs3600-ta@kurtis ~]$ emacs helloWorld.py &
[1] 3262

Here we gave the argumenthelloWorld.pywhich will either open that file for editing if it exists, or create it otherwise. Emacs notices that this is a Python source file (because of the.pyending) and enters Python-mode, which is supposed to help you write code. When editing this file you may notice some of that some text becomes automatically colored: this is syntactic highlighting to help you distinguish items such as keywords, variables, strings, and comments. Pressing Enter, Tab, or Backspace may cause the cursor to jump to weird locations: this is because Python is very picky about indentation, and Emacs is predicting the proper tabbing that you should use.

You can also copy and paste using just the mouse. Using the left button, select a region of text to copy. Click the middle button to paste.

There are two ways you can use Emacs to develop Python code. The most straightforward way is to use it just as a text editor: create and edit Python files in Emacs; then run Python to test the code somewhere else, like in a terminal window. Alternatively, you can run Python inside Emacs: see the options under "Python" in the menubar, or type C-c ! to start a Python interpreter in a split screen. (Use C-x o to switch between the split screens).

If you want to spend some extra set-up time becoming a power user, you can try an IDE like Eclipse(Download the Eclipse Classic package at the bottom). Check out PyDev for Python support in Eclipse.

Python Basics

The programming assignments in this course will be written inPython, an interpreted, object-oriented language that shares some features with both Java and Scheme. This tutorial will walk through the primary syntactic constructions in Python, using short examples.

You may find the Troubleshooting section at the end of this tutorial helpful if you run into problems. It contains a list of the frequent problems previous CS3600 students have encountered when following this tutorial.

Invoking the Interpeter

Like Scheme, Python can be run in one of two modes. It can either be usedinteractively, via an interpeter, or it can be called from the command line to execute ascript. We will first use the Python interpreter interactively.

You invoke the interpreter by enteringpythonat the Unix command prompt.Note: you may have to typepython2.4orpython2.5, rather thanpython, depending on your machine.

Operators

The Python interpeter can be used to evaluate expressions, for example simple arithmetic expressions. If you enter such expressions at the prompt (>>>) they will be evaluated and the result wil be returned on the next line.

>>> 1 + 1
2
>>> 2 * 3
6

Boolean operators also exist in Python to manipulate the primitiveTrueandFalsevalues.

We can also index multiple adjacent elements using the slice operator. For instancefruits[1:3]which returns a list containing the elements at position 1 and 2. In generalfruits[start:stop]will get the elements instart, start+1, ..., stop-1. We can also dofruits[start:]which returns all elements starting from thestartindex. Alsofruits[:end]will return all elements before the element at positionend:

Note: Ignore functions with underscores "_" around the names; these are private helper methods.

Tuples

A data structure similar to the list is thetuple, which is like a list except that it is immutable once it is created (i.e. you cannot change its content once created). Note that tuples are surrounded with parentheses while lists have square brackets.

The attempt to modify an immutable structure raised an exception. Exceptions indicate errors: index out of bounds errors, type errors, and so on will all report exceptions in this way.

Sets

Asetis another data structure that serves as an unordered list with no duplicate items. Below, we show how to create a set, add things to the set, test if an item is in the set, and perform common set operations (difference, intersection, union):

Note that the objects in the set are unordered; you cannot assume that their traversal or print order will be the same across machines!

Dictionaries

The last built-in data structure is thedictionarywhich stores a map from one type of object (the key) to another (the value). The key must be an immutable type (string, number, or tuple). The value can be any Python data type.

Note:In the example below, the printed order of the keys returned by Python could be different than shown below. The reason is that unlike lists which have a fixed ordering, a dictionary is simply a hash table for which there is no fixed ordering of the keys.

Remember that the print statements listing the costs may be in a different order on your screen than in this tutorial; that's due to the fact that we're looping over dictionary keys, which are unordered. To learn more about control structures (e.g.,ifandelse) in Python, check out the officialPython tutorial section on this topic.

If you like functional programming (like Lisp) you might also likemapandfilter:

Rather than having amainfunction as in Java, the__name__ == '__main__'check is used to delimit expressions which are executed when the file is called as a script from the command line. The code after the main check is thus the same sort of code you would put in amainfunction in Java.

Problem 1 (for submission):Add abuyLotsOfFruit(orderList)function tobuyLotsOfFruit.pywhich takes a list of(fruit,pound)tuples and returns the cost of your list. If there is somefruitin the list which doesn't appear infruitPricesit should print an error message and returnNone(which is likenilin Scheme). Please do not change thefruitPricesvariable.

Test Case:We will check your code by testing that the script correctly outputs

Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25

Advanced Exercise: Write a quickSort function in Python using list comprehensions. Use the first element as the pivot. Solution: quickSort.py

Object Basics

Although this isn't a class in object-oriented programming, you'll have to use some objects in the programming projects, and so it's worth covering the basics of objects in Python. An object encapsulates data and provides functions for interacting with that data.

The FruitShop class has some data, the name of the shop and the prices per pound of some fruit, and it provides functions, or methods, on this data. What advantage is there to wrapping this data in a class?

Encapsulating the data prevents it from being altered or used inappropriately,

The abstraction that objects provide make it easier to write general-purpose code.

Using Objects

So how do we make an object and use it? Download theFruitShopimplementation inshop.py. We then import the code from this file (making it accessible to other scripts) usingimport shop, sinceshop.py is the name of the file. Then, we can createFruitShopobjects as follows:

So what just happended? Theimport shopstatement told Python to load all of the functions and classes inshop.py. The lineberkeleyShop = shop.FruitShop(shopName, fruitPrices)constructs aninstanceof theFruitShopclass defined inshop.py, by calling the__init__function in that class. Note that we only passed two arguments in, while__init__seems to take three arguments:(self, name, fruitPrices). The reason for this is that all methods in a class haveselfas the first argument. Theselfvariable's value is automatically set to the object itself; when calling a method, you only supply the remaining arguments. Theselfvariable contains all the data (nameandfruitPrices) for the current specific instance (similar tothisin Java). The print statements use the substitution operator (described in thePython docsif you're curious).

Static vs Instance Variables

The following example with illustrate how to use static and instance variables in python.Create theperson_class.pycontaining the following code:

Problem 2 (for submission): Fill in the functionshopSmart(orders,shops)inshopSmart.py, which takes anorderList(like the kind passed in toFruitShop.getPriceOfOrder) and a list ofFruitShopand returns theFruitShopwhere your order costs the least amount in total. Don't change the file name or variable names, please. Note that we will provide theshop.pyimplementation as a "support" file, so you don't need to submit yours.

Test Case:We will check that, with the following variable definitions:

More Python Tips and Tricks

This tutorial has briefly touched on some major aspects of Python that will be relevant to the course. Here's some more useful tidbits:

Use range to generate a sequence of integers, useful for generating traditional indexed for loops:

for index in range(3): print lst[index]

After importing a file, if you edit a source file, the changes will not be immediately propagated in the interpreter. For this, use the reload command:

>>> reload(shop)

Troubleshooting

These are some problems (and their solutions) that new python learners commonly encounter.

Problem:
ImportError: No module named py

Solution:
When using import, do not include the ".py" from the filename.
For example, you should say: import shop
NOT: import shop.py

Problem:
NameError: name 'MY VARIABLE' is not defined
Even after importing you may see this.

Solution:
To access a member of a module, you have to type MODULE NAME.MEMBER NAME, where MODULE NAME is the name of the .py file, and MEMBER NAME is the name of the variable (or function) you are trying to access.

Problem:
TypeError: 'dict' object is not callable

Solution:
Dictionary looks up are done using square brackets: [ and ]. NOT parenthesis: ( and ).

Problem:
ValueError: too many values to unpack

Solution:
Make sure the number of variables you are assigning in a for loop matches the number of elements in each item of the list. Similarly for working with tuples.

For example, if pair is a tuple of two elements (e.g. pair =('apple', 2.0)) then the following code would cause the "too many values to unpack error":(a,b,c) = pair

If you are editing a file in a window different from the one you are using to execute python, make sure you reload(YOUR_MODULE) to guarantee your changes are being reflected. reloadworks similar to import.