Python Quick Reference, Assignments of Computer Science

A quick reference for python, including installation instructions, essential documents, data structures, indexing and slicing, length function, list methods, dictionaries, string operators and functions, and classes and objects. It also covers inheritance and the use of the string library.

Typology: Assignments

Pre 2010

Uploaded on 08/16/2009

koofers-user-6zy-2
koofers-user-6zy-2 🇺🇸

8 documents

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
COMP151 Python Quick Reference Page 1 of 13
Installation: Go to http://www.python.org/download/. If you are a windows user, download “Python 2.5 Windows installer”. The default installation
directory for Windows is C:\Python25.
Writing Python code: You can write Python code with any ASCII text editor. The Windows installation also comes with IDLE, the Python
development environment, which can be used to both write and run Python code. Your Python code files should always end in a .py suffix.
Running Python code: Since Python is an interpreted language, there is no separate compilation process (as there is in Java or C++). Simply call
the interpreter and pass it the name of the Python file containing your main program.
If you used the default installation path for Windows, the interpreter will be C:\Python25\python.exe. If you are running form the Windows
command line, you may want to add C:\Python25 to your Path environment variable (My Computer right-click Properties Advanced
Environment Variables).
If you are using IDLE, you can run the code in the editor by pressing F5 or Run Run Module.
Essential Documents:
Installing Python also installs a variety of useful documents. On Windows, the documents are accessible from START Programs Python 2.5
Python Manuals. These documents are also available online at http://docs.python.org/.
The primary documents of interest are “Tutorial” and “Library Reference”.
If you are new to Python, you should become familiar with the following chapters in the Tutorial:
3. An Informal Introduction to Python: numbers, strings and lists
4. More Control Flow: conditionals and loops
5. Data Structures: lists, tuples and dictionaries are essential – sequences and sets are less important
6. Modules: modules are how Python deals with multiple files and libraries
9. Classes: object-oriented concepts
The following are less critical, but still valuable:
7. Input and Output
8. Errors and Exceptions
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Python Quick Reference and more Assignments Computer Science in PDF only on Docsity!

Installation: Go to http://www.python.org/download/. If you are a windows user, download “Python 2.5 Windows installer”. The default installation

directory for Windows is C:\Python25.

Writing Python code: You can write Python code with any ASCII text editor. The Windows installation also comes with IDLE, the Python

development environment, which can be used to both write and run Python code. Your Python code files should always end in a .py suffix.

Running Python code: Since Python is an interpreted language, there is no separate compilation process (as there is in Java or C++). Simply call

the interpreter and pass it the name of the Python file containing your main program.

If you used the default installation path for Windows, the interpreter will be C:\Python25\python.exe. If you are running form the Windows

command line, you may want to add C:\Python25 to your Path environment variable (My Computer  right-click  Properties  Advanced

 Environment Variables).

If you are using IDLE, you can run the code in the editor by pressing F5 or Run  Run Module.

Essential Documents:

Installing Python also installs a variety of useful documents. On Windows, the documents are accessible from START  Programs  Python 2.

 Python Manuals. These documents are also available online at http://docs.python.org/.

The primary documents of interest are “ Tutorial ” and “ Library Reference ”.

If you are new to Python, you should become familiar with the following chapters in the Tutorial:

3. An Informal Introduction to Python: numbers, strings and lists

4. More Control Flow: conditionals and loops

5. Data Structures: lists, tuples and dictionaries are essential – sequences and sets are less important

6. Modules: modules are how Python deals with multiple files and libraries

9. Classes: object-oriented concepts

The following are less critical, but still valuable:

7. Input and Output

8. Errors and Exceptions

Essential Data Structures:

Lists: Lists are mutable ordered sequences. This makes them very flexible as they can also behave like many common data structures such as

queues and arrays. Lists are constructed with square brackets [ ].

Tuples: Tuples are immutable ordered sequences. Tuples are best used for packing values into a single structure, rather than for dynamic

structures. Tuples are constructed as comma-separated values. They may be enclosed in parentheses ( ), which may be required in some contexts.

Dictionaries: Dictionaries define a mapping from keys to values. Other languages call these maps or associative arrays. Dictionaries are

constructed with braces { }.

Strings: Strings are sequences of characters. Strings are immutable. Strings can be defined with double or single quotes (e.g. “foo” or ‘bar’).

Examples:

>>> s = "a string" # a string of length 8

>>> t = 'a string' # a string of length 8

>>> a = ['spam', 'eggs', 100, 1234] # a list of 4 elements

>>> b = [ ] # an empty list

>>> c = 1, 2, 3 # a tuple of three elements

>>> d = (1,2,3) # a tuple of three elements

>>> e = ( ) # an empty tuples

>>> f = 'spam', # a tuple with one element (comma is required!)

>>> g = ('spam',) # a tuple with one element (comma is required!)

>>> h = {'x':1, 'y':2, 'z':2} # a dictionary mapping strings to integers

>>> i = {1:'x', 2:'y', 3:'z'} # a dictionary mapping integers to strings

>>> j = {} # a empty dictionary

Length function: len(x) returns the number of elements in structure x. It can be applied to lists, strings, tuples and dictionaries.

Useful list methods: These are methods (rather than free functions) and require x.f() notation, where x is the list.

a.append(x): Add item x to the end of the list, equivalent to a[len(a):] = [ x ].

a.extend(L): Extend the list a by appending all the items in the given list; equivalent to a[len(a):] = L.

a.insert(i,x): Insert an item at a given position. The first argument is the index of the element before which to insert,

so a.insert(0, x ) inserts at the front of the list, and a.insert(len(a), x ) is equivalent to a.append( x ).

a.remove(x): Remove the first item from the list whose value is x. It is an error if there is no such item.

a.pop([I]): Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the

last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional)

a.index(x): Return the index in the list of the first item whose value is x. It is an error if there is no such item.

a.count(x): Return the number of times x appears in the list.

a.sort(): Sort the items of the list, in place.

a.reverse(): Reverse the elements of the list, in place.

Using Lists as Stacks or Queues:

stack = [3, 4, 5] stack.append(6) stack.append(7) stack [3, 4, 5, 6, 7] stack.pop() 7 stack [3, 4, 5, 6] stack.pop() 6 stack.pop() 5 stack [3, 4] queue = ["Eric", "John", "Michael"] queue.append("Terry") # Terry arrives queue.append("Graham") # Graham arrives queue.pop(0) 'Eric' queue.pop(0) 'John' queue ['Michael', 'Terry', 'Graham']

Dictionaries: Dictionaries are indexed by keys, rather than positions. Dictionaries are mutable, in that the value associated with a key may be

changed.

>>> d = { 'COMP51' : 'Cliburn', 'COMP53' : 'Carman', 'COMP151':'Doherty' }

>>> d

{'COMP51': 'Cliburn', 'COMP53': 'Carman', 'COMP151': 'Doherty'}

>>> d['COMP51']

'Cliburn'

>>> d['COMP51'] = 'Topp'

>>> d['COMP51']

'Topp'

Operator precedence: Operators higher in the table have higher precedence.

Operator Description number of operands

or logical OR binary

and logical AND binary

not x logical NOT unary

relational (comparison)

binary

+, - addition/concatenation and subtraction binary

*, /, % multiplication, division, remainder binary

+ x , - x positive, negative unary

** exponentiation binary

x [ index ] indexing binary

x [ index : index ] slicing trinary

Functions provided by the string library (requires import string): In first column: s, t represent string values, n represents integer values and list represents a list of strings. function return type description example center(s, n) string Create a new string of n characters with s in the center. Remaining characters are spaces.

string.center('dog',8) queue.pop(0) 'John' >>> queue ['Michael', 'Terry', 'Graham'] ## Dictionaries: Dictionaries are indexed by keys, rather than positions. Dictionaries are mutable, in that the value associated with a key may be ## changed. ## >>> d = { 'COMP51' : 'Cliburn', 'COMP53' : 'Carman', 'COMP151':'Doherty' } ## >>> d ## {'COMP51': 'Cliburn', 'COMP53': 'Carman', 'COMP151': 'Doherty'} ## >>> d['COMP51'] ## 'Cliburn' ## >>> d['COMP51'] = 'Topp' ## >>> d['COMP51'] ## 'Topp' ## Operator precedence: Operators higher in the table have higher precedence. ## Operator Description number of operands ## or logical OR binary ## and logical AND binary ## not x logical NOT unary ## relational (comparison) ## binary ## +, - addition/concatenation and subtraction binary ## *, /, % multiplication, division, remainder binary ## + x , - x positive, negative unary ## ** exponentiation binary ## x [ index ] indexing binary ## x [ index : index ] slicing trinary Functions provided by the string library (requires import string): In first column: s, t represent string values, n represents integer values and list represents a list of strings. function return type description example center(s, n) string Create a new string of n characters with s in the center. Remaining characters are spaces. >>> string.center('dog',8) ' dog ' ljust(s, n) string Create a new string of n characters with s at the left. Remaining characters are spaces. string.ljust('dog',8) 'dog rjust(s, n) string Create a new string of n characters with s at the right. Remaining characters are spaces. string.rjust('dog',8) ' dog' strip(s) string Create a copy of s with leading and trailing whitespace removed. string.strip(' cat ') 'cat' lstrip(s) string Create a copy of s with leading whitespace removed. string.lstrip(' cat ') 'cat ' rstrip(s) string Create a copy of s with trailing whitespace removed. string.lstrip(' cat ')

' cat' capitalize(s) string Create a copy of s with the first character capitalized.

string.capitalize('driver disk')

'Driver disk' capwords(s) string Create a copy of s with the first character in each word capitalized. (Words are separated by whitespace)

string.capwords('three short words')

'Three Short Words' upper(s) string Create a copy of s with all letters converted to upper-case.

string.upper('this is loud') 'THIS IS LOUD' lower(s) string Create a copy of s with all letters converted to lower-case. string.lower('A funKY StriNG') 'a funky string' split(s) list of strings Split a string into a list of substrings. Strings are split at whitespace (word boundaries). string.split('Break this apart.') ['Break', 'this', 'apart.'] split(s, t) list of strings Split a string into a list of substrings. Strings are split at occurrences of the string t. string.split('Break this apart.', 'a') ['Bre', 'k this ', 'p', 'rt.'] join(list) string Concatenate all string in a list to create a single string. list = [ 'One', 'Two', 'Three' ] string.join(list) 'One Two Three'

Functions provided by the string library (requires import string): In first column: s, t and u represent string values. function return type description example count(s, t) integer Determine the number of times that t appears in s.

s = 'Mississippi' string.count(s, 'iss') 2 string.count(s, 'issi') 1 string.capitalize('driver disk') 'Driver disk' capwords(s) string Create a copy of s with the first character in each word capitalized. (Words are separated by whitespace) >>> string.capwords('three short words') 'Three Short Words' upper(s) string Create a copy of s with all letters converted to upper-case. >>> string.upper('this is loud') 'THIS IS LOUD' lower(s) string Create a copy of s with all letters converted to lower-case. >>> string.lower('A funKY StriNG') 'a funky string' split(s) list of strings Split a string into a list of substrings. Strings are split at whitespace (word boundaries). >>> string.split('Break this apart.') ['Break', 'this', 'apart.'] split(s, t) list of strings Split a string into a list of substrings. Strings are split at occurrences of the string t. >>> string.split('Break this apart.', 'a') ['Bre', 'k this ', 'p', 'rt.'] join(list) string Concatenate all string in a list to create a single string. >>> list = [ 'One', 'Two', 'Three' ] >>> string.join(list) 'One Two Three' Functions provided by the string library (requires import string): In first column: s, t and u represent string values. function return type description example count(s, t) integer Determine the number of times that t appears in s. >>> s = 'Mississippi' >>> string.count(s, 'iss') 2 >>> string.count(s, 'issi') 1 find(s, t) integer Determine the position (index) of the first occurrence of t in s, looking from the left. s = 'Mississippi' string.find(s, 'iss') 1 rfind(s, t) integer Determine the position (index) of the first occurrence of t in s, looking from the right. s = 'Mississippi' string.rfind(s, 'iss') 4 replace(s, t, u) string Make a copy of s in which all occurrences of t have been replaced by u. x = 'banana' string.replace(x, 'an', '-an') 'b-an-ana'

In our example, the constructor creates and initializes a single instance variable called self.count. Thus, the statement my_counter = Counter(), creates an object that looks like: Notice how the variable self.count is encapsulated inside the object named counter. We manipulate objects by calling the methods on the object, with the object named pre-pended with a dot. The object name actually gets used as the first parameter to the method, thus the object name becomes associated with the self argument. Thus, the statement my_counter.increment() adds 1 to the count variable inside the object named my_counter. We can create multiple object of the same type, and each has its own copy of the instance variables. For example: my_counter (^) self.count

my_counter (^) self.count

c1 = Counter() c2 = Counter() c1.increment() c1.increment() c2.increment() print c1.getCount(), c2.getCount # prints 2 1

produces the following objects: Here’s an example of a class that defines objects with two instance variables. c1 (^) self.count

c2 (^) self.count

class Scoreboard: def init(self): self.home = 0 self.away = 0 def addHome(self, points): self.home = self.home + points def addAway(self, points): self.away = self.away + points def homeScore(self): return self.home def awayScore(self): return self.away def printScore(self): print "Home:", self.home, "Away:", self.away

Consider what will happen if we run the following code: At the end, we will have the following objects:

Inheritance: A class can be derived from another class through inheritance. The base class is indicated in parentheses in the declaration of the

derived class. A derived class automatically has all methods defined for the base class.

p1 = Point(10, 20) p2 = Point(100, 112) p1.move(200, 0) p2.move(50, –50) print p1.getX(), p1.getY() print p2.getX(), p2.getY() p1 (^) self.x 210 self.y 20 p2 (^) self.x 150 self.y 62 class ColoredPoint(Point): def init(self, x, y, color): Point.init(self,x,y) self.color = color def getColor(self): return self.color c = ColoredPoint(1,2,'red') print c.getX(), c.getY(), c.getColor()