Python language
Intro
1
Resources
• http://www.python.org/
– Python tutorial
• http://www.python.org/doc/current/tut/tut.html
– Python library reference
• http://www.python.org/doc/current/lib/lib.html
• http://pydoc.org/
– Python documentation
• Nutshell Books Online (at UMD)
– http://proquest.safaribooksonline.com/0596000855
– http://proquest.safaribooksonline.com/0596002815
2
Python
• The interpreter
– Starting python, interpreting statements, import
• Variables, types
– Integers, floats, booleans, strings, lists, tuples,
dictionaries
• Conditionals
• Iteration
• Functions
• Input and output
• Classes (object-oriented programming)
– Constructors 3
The Interpreter
• Starting python
– Interactive mode
• In Unix, typically type “python”
• python [-i ]
– Non-interactive mode
• python
• Interactive mode: statements directly interpreted
– E.g.,
a = 10 ## assign variable „a‟ the value 10
– Typing and will give you value
of variable in interactive mode
• import statement lets you read in other files
– These are called “modules” in Python
– Objects are qualified by the module name
– Don‟t supply the .py extension
– E.g.,
4
import lab1 ## imports lab4.py
import sys ## a standard library; so we can use the write function
Variables, types
• Python is an interpreted, loosely typed language
– You can dynamically change the types of variables
– Variables are implicitly declared when you assign to
them for the first time
• Example
chris% python
Python 2.2 (#1, 11/12/02, 23:31:59)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a=10
>>> a = "abc"
>>> a = [1, 2, 3, 4]
>>>
• Variable names are case sensitive
A = 10
5
a = 10 ## two variables with value 10
Built-in Primitive Types
• Integers
• Strings; “abc”, „abc‟, „‟(empty string)
– Immutable
– Definition: The contents of an immutable object cannot
be changed on the basis of a reference to the immutable
object; The contents of a mutable object can be
changed on the basis of a reference to the mutable
object
• Long integers (unlimited size); a = 1000L
• booleans (Python 2.3)
• floating point
• complex numbers; 3+4j 6
Nesting in Python
• Use white space to indicate sub-ordinate
statements
– I.e., like the “{“ and “}” in C and C++
7
String Operations - 1
• Concatenate: +
>>> 'a‟ + 'bc'
'abc'
• Repeat: *
>>> "a” * 10
'aaaaaaaaaa'
• Index: [i]
– Indices start (left) at 0; negative indices start at right; -1
rightmost
>>> "abcd"[-1]
'd'
>>> "abcd"[-2]
'c' 8
String Operations - 2
• [i:j] (slice)
– Return a substring starting at position i, and going until
position j-1
– Either i or j can be unspecified, which means the start
or end of the string respectively len(aString) (length)
>>> "abcd"[1:]
'bcd‟
>>> "abcd"[:-2]
'ab'
for x in "abcd":
• Iteration print x
for aChar in aString: a
b
c
Note: indentation is d
necessary part of syntax 9
String Operations - 3
• len(s): length
• aChar in string (membership test; typically
use in a conditional)
>>> "a" in "abcd"
True
• Other operations
– See the Python string module
import string
10
Example - 1
• Write a Python program to reverse a string
(in general), within what we have covered
so far
– The string will be contained in a variable, S
– I.e., S = “abc” should be reversed to “cba”
11
Structured Types: Lists
• Mutable, square bracketed, comma separated
– Contain any objects
– E.g.
[1, 2, 3]
[„a‟, 1, “hi there”, [1, 2]]
• Operators
– Index, slice, length (len), concatenate (+), repeat (*),
iteration (for … in …) , membership (in)
• Methods
– append, sort, index, reverse, del (delete)
• Syntax for delete:
del a[k]
– index and slice assignment
12
– range, xrange
Changing Lists
a = [1, 2, 3, 4]
a[0] = „left‟ ## change leftmost element
a[-1] = „right‟ ## change rightmost element
## a now is ['left', 2, 3, 'right']
a[1:3] = ['a', 'b', 'c', 'd', 'e', 'f']
## a now is ['left', 'a', 'b', 'c', 'd', 'e', 'f', 'right']
13
for x in theList
• This iterator structure causes the iterator variable (e.g., x)
to take on each value in the list, successively
– Example
for x in [8, 2, 6, -99]:
print x
– Output:
8
2
6
-99
14
Example - 2
• Increment each item of an arbitrary length
integer list by 10
Watch out for the trap!
15
Solution
l = [1, 2, 3, 4]
i=0
for x in l:
l[i] = l[i] + 10
i = i+1
print l
Output
[11, 12, 13, 14] 16
Example - 3
• In each iteration, x takes on the value of a list
element but is not a reference that will allow
changing the element itself within the containing
list (theList)
theList = [8, 2, 6, -99]
for x in theList:
x += 10 Output
print x 18
print theList 12
16
(Likely INCORRECT-- -89
probably not what you want [8, 2, 6, -99] 17
to do!)
Some of the Other
Operations on Lists
>>> l = [1, 2, 3, 4]
>>> l.append(5)
>>> l
[1, 2, 3, 4, 5]
>>> del l[0]
>>> l
[2, 3, 4, 5]
>>> range(10) (Convenient for
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] controlling iteration.) 18
Typical Python Iteration
l = [6, 16, -3, 90]
for x in range(len(l)):
l[x] = l[x] + 10
print l
19
Structured types: Dictionaries
• Unordered, mutable collections, accessed by key
• Each dictionary entry is a pair:
– key, value
• Syntax: Surrounded with “{“, “}” brackets
• Example
d = {} ## empty dictionary
months = {'Jan' : 31, 'Feb' : 28, 'Mar' : 31, 'Apr' : 30,
'May' : 31, 'Jun' : 30, 'Jul' : 31, 'Aug' : 31, 'Sep' : 30,
'Oct' : 31, 'Nov' : 30, 'Dec' : 31}
20
Dictionaries: Operations
• Indexing
months[„Jan‟] ## 31
• Add a new entry
months[„December‟] = 31 ## just index with new key
• has_key: test if a key has an associated value
months.has_key(„Jan‟) ## 1
months. has_key(„January‟) ## 0
• keys: return a list of keys for the dictionary
months.keys() ## returns list of month names
• values: return list of values associated with keys
months.values() // may have duplicates
• for x in aDictionary
x takes on successive key values
21
• len (length), del (delete)
Example
months = {'Jan' : 31, 'Feb' : 28, 'Mar' : 31, 'Apr' : 30,
'May' : 31, 'Jun' : 30, 'Jul' : 31, 'Aug' : 31, 'Sep' : 30,
'Oct' : 31, 'Nov' : 30, 'Dec' : 31}
for m in months:
print m, ## comma means don‟t output newline
• OUTPUT
Mar Feb Aug Sep May Jun Jul Jan Apr Nov Dec Oct
(Note: the order of keys is 22
implementation dependent)
Example - 3.1
• Given the months dictionary, months, sum
up the number of days in all months
months = {'Jan' : 31, 'Feb' : 28, 'Mar' : 31, 'Apr' : 30,
'May' : 31, 'Jun' : 30, 'Jul' : 31, 'Aug' : 31, 'Sep' : 30,
'Oct' : 31, 'Nov' : 30, 'Dec' : 31}
23
Solution
months = {'Jan' : 31, 'Feb' : 28, 'Mar' : 31, 'Apr' : 30,
'May' : 31, 'Jun' : 30, 'Jul' : 31, 'Aug' : 31, 'Sep' : 30,
'Oct' : 31, 'Nov' : 30, 'Dec' : 31}
result = 0
for m in months:
result += months[m]
24
Structured types: Tuples
• Like lists, except that they are immutable
– Operations on lists are available except those
that change the tuple in-place (e.g., append, del)
• Usually written with “(“, “)” instead of
square brackets (lists)
• In some cases, can omit the “(“, “)” brackets
• Examples
t1 = () ## empty tuple
t2 = (6,) ## one item tuple
## Note that (6) is just the value 6 and not a tuple
t3 = 2, 3 ## two item tuple 25
t4 = (2, 3) ## same two item tuple
Defining Functions
• Syntax:
def (parameter1, …):
indented statements in body…
## optional return statement(s)
• In Python, arguments can be specified by name, in
any order.
• Optional arguments:
def (parameter1,
OptionalParam2=default value):
indented statements in body…
## optional return statement(s) 26
Example - 4
• Write a function that accepts a tuple and returns a
new tuple, in reverse order
t = („a‟, „b‟, „c‟)
print TupleReverse(t)
## Output: („c‟, „b‟, „a‟)
• HINT: This is a little tricky; watch out for the
syntax of single item tuples
27
Solution
def TupleReverse(t):
result = ()
for elem in t:
result = (elem,) + result
return result Output
(1,)
print TupleReverse((1,)) (2, 1)
print TupleReverse((1, 2)) ('rr', 'x', 'a')
print TupleReverse(("a", "x", "rr"))
28
Lambda Functions
• Functions created without a specific name
• Syntax:
lambda arg1, arg2, … argN:
Single-line expression using arguments
• Semantics:
– Creates a function with N arguments, that when called evaluates
the expression
• Example
f = lambda a, b, c: a+b+c ## assigns a function object to a
## variable, f
print f(1, 2, 3) ## prints 6
29
Can use def to do same thing
def fun(op1, op2, …):
return expression
f = fun
E.g.,
def fun(a, b, c):
return a + b + c
f = fun ## f is a function variable
## fun is a function constant
print f(1, 2, 3) 30
Multiple Assignment Statements
[x, y] = [1, 2]
(a, b, c) = (3, 4, 10)
31
Returning a Tuple From a
Function
def retPair():
a = 10
b = "abc"
return a, b
x, y = retPair()
## also: (x, y) = retPair()
OUTPUT:
print x
10
print y abc
z = retPair() (10, 'abc')
32
print z
Checking the Type of an Object
• type(value) returns the type of the value
– Value can be a parameter or variable
• E.g.,
>>> x = 10
>>> type(x)
if (type(x) == type(5)):
print “Is an integer”
• Unfortunately, is not a valid constant 33
Control Structures
if :
And, or, not: specified using
and, or, not
elif :
Equality comparisons
else: ==
!=
34
Example
• Write a recursive function that flattens a list by
removing all nesting structure from the list--
flatten returns all the non-list components of the
passed list, in a list
• Examples
flatten([]) ==> []
flatten([[],[]]) ==> []
flatten([1, [2, 3]]) ==> [1, 2, 3]
flatten([[[„a‟]]]) ==> [„a‟]
35
Classes
• Syntax:
class ClassName:
## Functions defined in this class are scoped
## to this class.
## constructor: __init__
## self is like „this‟ in C++, a reference to object
## when you invoke a method object.method
## object gets passed, automatically, as the first parameter
def __init__(self):
## body of constructor, indented
def othermethod(self):
## body
36
class AgentBrain: Example
## constructor
def __init__(self):
self.data = 0 ## instance data
def set(self, value):
self.data = value
def get(self):
return self.data
>>> r = AgentBrain()
>>> r.get()
0
>>> r.set(10)
>>> r.get()
10 37
Classes: Instance &
Class Data
• Syntax:
class ClassName:
data1 = value1 ## per class
def __init__(self):
self.data2 = value2 ## per instance
## body of constructor, indented
## refer to per class data with qualifier
ClassName.data1 = “blah”
def othermethod(self):
## body
38
Example - 5
• Write a class that counts the number of
class instances that have been created, and
outputs that value when each new instance
is created
39
Solution
class CountInstance:
count = 0
## constructor
def __init__(self):
CountInstance.count += 1
print CountInstance.count
## May not get called!
def __del__(self):
CountInstance.count -= 1
print CountInstance.count 40
Other Methods to Overload
__add__
Addition operator
__or__
Bitwise or operator („|‟)
__repr__
Return the “official” string representation
__getitem__, __setitem__
Indexing & indexing assignment
41
Example
• Write a function that tests if all non-list
elements in an arbitrarily nested list are of
the same type
• SameType([“a”]) returns True
• SameType([1, [2, 3], []]) returns True
• SameType([1, [[“a”]]]) returns False
42
While loop
while :
## can have break, continue statements
else: ## optional
## run if didn‟t exit with break
43
i = 10
Examples
while i >= 1:
print i,
i -= 1
else:
print "Done loop"
i = 10
while 1 == 1:
print i,
i -= 1
if i == 0:
break
else:
print "Done loop"
OUTPUT:
chris% python while1.py
10 9 8 7 6 5 4 3 2 1 Done loop 44
10 9 8 7 6 5 4 3 2 1
for Loops
for in :
## possible break or continue
else:
## run if didn‟t exit with break
45
Traditional for Iteration
• Say we want to iterate with i=1 to 100
• Use the range or xrange list constructors
– These let you generate lists of consecutive integer
values
range(5) returns [0, 1, 2, 3, 4]
range(1, 5) returns [1, 2, 3, 4]
– In general: range(start, end, step)
• So, can use this in a for loop to iterate over a
series (i.e., range) of integers
for x in range(5):
xrange generates integers one
print x, at a time; may be more
OUTPUT: efficient for iteration over large
01234 ranges of values
Input and Output
• Character by character output
import sys
sys.stdout.write(“hello”)
sys.stdout.write(“there”)
OUTPUT:
hellothere
• Write requires a string parameter
– To pass it non-string parameters, convert with
function str
a = str(123) ## convert integer to string See:
b = str(1.23) http://pydoc.org/
c = str((1, 2, 3)) ## convert tuple to string 47
d = str([1, 2, 3]) ## convert list to string
Input from Console
import sys
print "Please type 2 keys (including enter) to continue"
inChar = sys.stdin.read(2)
## read 2 characters from user, but must type at least one "enter"
## type of inChar is string; read method returns a string
print "Please enter a line"
inString = sys.stdin.readline()
## type of inString is still a string; inString will contain the return
print "Inputs: ", inChar, inString
print "Please press enter to continue" 48
sys.stdin.read(1) ## suitable for getting newline
import and reload
import lab2
– lab2 functions & data must be qualified with
module name
– Only works once, cannot be used to reload
changes
reload(lab2) ## note the parentheses
– Only works if a module was loaded
successfully, previously
49
from x import y
• Loads names in list y from module x
– Only loads those names listed in y
– Runs the program code in the associated
module (i.e., code that is in global scope, and
not in function or class)
– Variables and functions NOT qualified by the
module (i.e., file) name
• PYTHONPATH environment variable is
searched
50
>>> import example
example.py hello
>>> example.y
100
print "hello" >>> example.x
'there‟
>>> example.TestFun()
def TestFun(): 'there'
return "there" >>> x
Traceback (most recent call last):
File "", line 1, in ?
x = TestFun() NameError: name 'x' is not defined
>>> y
Traceback (most recent call last):
y = 100 File "", line 1, in ?
NameError: name 'y' is not defined
example.py >>> from example import *
hello
>>> example.y
print "hello" Traceback (most recent call last):
File "", line 1, in ?
def TestFun(): NameError: name 'example' is not defined
return "there" >>> example.x
Traceback (most recent call last):
File "", line 1, in ?
x = TestFun() NameError: name 'example' is not defined
>>> x
y = 100 'there'
>>> y
100
52
Packages-- Example
QuickTime™ and a
TIFF (LZW) decompressor
are neede d to see this picture.
53
Example
from pyro.brain import Brain
## on my system pyro is rooted at /usr/local/pyro
## and this causes the directory /usr/local/pyro/brain
## to be searched; it finds the definition for
## Brain in the file
## named __init__.py
54