DM828 -- Python tutorialThis is a short Python tutorial reproduced here from Stanford University. It assumes that you have access to the IMADA machines where python is already installed.Python BasicsThe programming assignments in this course will be in Python, an interpreted, object-oriented language that shares some features with both Java and Scheme (from which R derives as well). This tutorial will walk through the primary syntactic constructions in Python, using short examples. More thorough tutorials on python are available at:
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. Invoking the Interpeter
You invoke the interpreter by entering
Operators
The Python interpeter can be used to evaluate expressions, for example
simple arithmetic expressions. If you enter such expressions at the
prompt (
The ** operator in the last example corresponds to
exponentiation.
Boolean operators also exist in Python to manipulate the primitive True and False values.
>>> 1==0
You can also use the “not” operator to negate a boolean expression:
>>> not (1==0)
Strings
Like Java, Python has a built in string type. The
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 strings.
We can also store expressions into variables.
In Python, unlike Java or C, you do not have declare variables before you assign to them. However, read this thread for a distinction between global and local variables. Exercise: Learn about the methods Python provides for
strings. To do this use the
Try out some of the string functions listed in 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. This is how many errors will manifest: 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): >>> shapes = ['circle','square','triangle','circle'] >>> setOfShapes = set(shapes) >>> setOfShapes set(['circle','square','triangle']) >>> setOfShapes.add('polygon') >>> setOfShapes set(['circle','square','triangle','polygon']) >>> 'circle' in setOfShapes True >>> 'rhombus' in setOfShapes False >>> favoriteShapes = ['circle','triangle','hexagon'] >>> setOfFavoriteShapes = set(favoriteShapes) >>> setOfShapes - setOfFavoriteShapes set(['square','polyon']) >>> setOfShapes & setOfFavoriteShapes set(['circle','triangle']) >>> setOfShapes | setOfFavoriteShapes set(['circle','square','triangle','polygon','hexagon']) 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.
As with nested lists, you can also create dictionaries of dictionaries. Exercise: Use Writing Scripts Now that you've got a handle on using Python interactively, let's
write a simple Python script that demonstrates Python's
At the command line, use the following command in the directory containing foreach.py:
Beware of Indendation!Unlike many other languages, Python uses the indentation in the source code for interpretation. So for instance the 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! Its best to use a single tab for indentation.
The next snippet of code demonstrates python's list comprehension construction:
Put this code into a file called listcomp.py and run the script:
If you like functional programming (like Scheme) you might also like map and filter: >>> map(lambda x: x * x, [1,2,3]) [1, 4, 9] >>> filter(lambda x: x > 3, [1,2,3,4,5,4,3,2,1]) [4, 5, 4] The map is similar to the list comprehension. You can learn more about lambda if you're interested. Exercise: Write a list comprehension which, from a list, generates a lowercased version of each string that has length greater than five. Solution Writing FunctionsYou can define your own functions: fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75} def buyFruit(fruit, numPounds): if fruit not in fruitPrices: print "Sorry we don't have %s" % (fruit) else: cost = fruitPrices[fruit] * numPounds print "That'll be %f please" % (cost) # Main Function if __name__ == '__main__': buyFruit('apples',2.4) buyFruit('coconuts',2) Rather than having a Save this script as fruit.py and run it:
Exercise: Add some more fruit
to the
This function should be defined in a file called Test Case:You can "sanity check" this portion of your code by testing that
Advanced Exercise: Write a Object BasicsAn object (class) encapsulates data and provides functions for interacting with that data. Here's a definition example:
The What advantage is there to wrapping this data in a class? There are
two reasons: So how do we make an object and use it? Download the
Copy the code above into a file called shopTest.py (in the same directory as shop.py) and run it:
So what just happended? The import shop statement told Python to load all of the functions and classes in shop.py.
These import statements are used more generally to load code modules. The line myFruitShop = shop.FruitShop(name, 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 by the interpreter; 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.
Static vs Instance VariablesThe following example with illustrate how to use static and instance variables in python. Create theperson_class.py containing the following code:
class Person: population = 0 def __init__(self, myAge): self.age = myAge Person.population += 1 def get_population(self): return Person.population def get_age(self): return self.age We first compile the script:
[dm828@woglinde ~/tutorial]$ python person_class.py
Now use the class as follows: >>> import person_class >>> p1 = person_class.Person(12) >>> p1.get_population() 1 >>> p2 = person_class.Person(63) >>> p1.get_population() 2 >>> p2.get_population() 2 >>> p1.get_age() 12 >>> p2.get_age() 63 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.
Exercise: Write a function,
This function should be defined in a file called Test Case: You can check that, with the following variable definitions:
The following are true:
and
Tricks and TipsHere are some more useful bits of information:
Note that indices start from 0. Last modified: Mon Nov 7 18:50:14 CET 2011 |