Python BasicsTable of Contents
Python BasicsThe programming assignments in this course will be written in Python, 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 helpful if you run into problems. It contains a list of the frequent problems previous cse511a students have encountered when following this tutorial. Invoking the InterpreterLike Scheme, Python can be run in one of two modes. It can either be used interactively, via an interpeter, or it can be called from the command line to execute a script. We will first use the Python interpreter interactively. Really cool people also use iPython which is a much more powerful and user-friendly interface to python. On shell.cec.wustl.edu (and most Wash U. computers) this is already pre-installed. (You can install it on your Mac with the command:sudo easy_install ipython . On Linux, apt-get install ipython should do the trick.)
You invoke the interpreter by entering python (or ipython ) at the Unix command prompt.
Note: you may have to type python2.4 or python2.5 , rather than python , depending on your machine.
OperatorsThe 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 will be returned on the next line.
Boolean operators also exist in Python to manipulate the primitive True and False values.
StringsLike Java, Python has a built in string type. The+ operator is overloaded
to do string concatenation on string values.
There are many built-in methods which allow you to manipulate strings.
>>> 'artificial'.upper()
Notice that we can use either single quotes ' ' or double quotes " "
to surround string. This allows for easy nesting of strings.
We can also store expressions into variables.
In Python, you do not have declare variables before you assign to them. Exercise: Learn about the methods Python provides for strings.
To see what methods Python provides for a datatype, use the Built-in Data StructuresPython comes equipped with some useful built-in data structures, broadly similar to Java's collections package.ListsLists store a sequence of mutable items:
We can use the + operator to do list concatenation:
Python also allows negative-indexing from the back of the list.
For instance, fruits[-1] will access the last
element 'banana' :
We can also index multiple adjacent elements using the slice operator. For instance fruits[1:3] which returns a list containing
the elements at position 1 and 2. In general fruits[start:stop]
will get the elements in start, start+1, ..., stop-1 . We can
also do fruits[start:] which returns all elements starting from the start index. Also fruits[:end] will return all elements before the element at position end :
The items stored in lists can be any Python data type. So for instance
we can have lists of lists:
Exercise: Play with some of the list functions. You can find the methods you can call on an object via the dir and
get information about them via the help command:
>>> help(list.reverse) Help on built-in function reverse: reverse(...) L.reverse() -- reverse *IN PLACE*
>>> lst = ['a','b','c']
Note: Ignore functions with underscores "_" around the names; these are private helper methods.
TuplesA data structure similar to the list is the tuple, 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.
SetsA set is 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!
DictionariesThe last built-in data structure is the dictionary which 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 (see the FAQ about dictionary key ordering).
As with nested lists, you can also create dictionaries of dictionaries. Exercise: Use Writing ScriptsNow that you've got a handle on using Python interactively, let's write a simple Python script that demonstrates Python'sfor loop. Open the file called foreach.py and update it with the following code:
At the command line, use the following command in the directory
containing foreach.py :
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., if and else ) in Python, check out the official Python tutorial section on this topic.If you like functional programming (like Scheme) you might also like map and filter :
You can learn more about lambda if you're interested.
The next snippet of code demonstrates python's list comprehension construction:
This code is in a file called listcomp.py , which you can run:
Those of you familiar with Scheme, will recognize that the list comprehension is similar to the
map function. In Scheme, the first list comprehension would be
written as:
(define nums '(1,2,3,4,5,6)) (map (lambda (x) (+ x 1)) nums)Exercise: Write a list comprehension which, from a list, generates a lowercased version of each string that has length greater than five. Solution: listcomp2.py
Beware of Indentation!Unlike many other languages, Python uses the indentation in the source code for interpretation. So for instance, for the following script:if 0 == 1: print 'We are in a world of arithmetic pain' print 'Thank you for playing'will output
But if we had written the script as
there would be no output. The moral of the story: be careful how you indent! It's best to use four spaces for indentation -- that's what the course code uses.
Writing FunctionsAs in Scheme or Java, in Python you can define your own functions:
Rather than having a main function 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 a main function in Java.Save this script as fruit.py and run it:
Exercise: Now would be a good time to complete Problem 1 of Project 0. Advanced Exercise: Write a quickSort function in
Python using list comprehensions. Use the first element as the
pivot. Solution: quickSort.py
Object BasicsAlthough 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.Defining ClassesHere's an example of defining a class namedFruitShop :
The
Using ObjectsSo how do we make an object and use it? Download theFruitShop implementation in shop.py .
We then import the code from this file (making it accessible to other scripts) using import shop , since shop.py is the name of the file. Then, we can create FruitShop objects as follows:
You can download this code in shopTest.py and run it like this:
So what just happened? The import shop statement told Python to load all of the functions and classes in shop.py .
The line berkeleyShop = shop.FruitShop(shopName, fruitPrices) constructs an instance of the FruitShop class defined in shop.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 have self as the first argument. The self variable's value is automatically set to the object
itself; when calling a method, you only supply the remaining arguments. The self variable contains all the data (name and fruitPrices ) for the current specific instance (similar to this in Java).
The print statements use the substitution operator (described in the Python docs if you're curious).
Static vs Instance VariablesThe following example with illustrate how to use static and instance variables in python.Create the person_class.py containing the following code:
We first compile the script:[cse511a-ta@shell ~]$ python person_class.py Now use the class as follows:
>>> import person_class
In the code above, age is an instance variable and population is a static variable.
population is shared by all instances of the Person class whereas each instance has its own age variable.
Now that you've just about completed the tutorial, try Problem 2 from Project 0.
More Python Tips and TricksThis tutorial has briefly touched on some major aspects of Python that will be relevant to the course. Here's some more useful tidbits:
TroubleshootingThese are some problems (and their solutions) that new python learners commonly encounter.
More References!
|