Python Tutorial
Python Tutorial
Python
Why Python?
Very Object Oriented
Python much less verbose than Java
Technical Issues
Installing & Running Python
% python
Python 2.5 (r25:51908, May 25 2007, 16:14:04)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
The Basics
A Code Sample
x = 34 - 23
y = Hello
z = 3.45
if z == 3.45 or y ==
x = x + 1
y = y +
World
print x
print y
# A comment
# Another one.
Hello :
# String concat.
Basic Datatypes
Integers (default for numbers)
z = 5 / 2
Floats
x = 3.456
Strings
Can use
or
to specify.
abc
abc (Same thing.)
Unmatched can occur within the string.
matt s
Use triple double-quotes for multi-line strings or strings than contain
both and inside of them:
a b c
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines.
Use a newline to end a line of code.
Use \ when must go to next line prematurely.
Comments
Start comments with # the rest of line is ignored.
Can include a documentation string as the first line of
any new function or class that you define.
The development environment, debugger, and other tools
use it: it s good style to include one.
def my_function(x, y):
This is the docstring. This
function does blah blah blah.
# The code would go here...
Assignment
Binding a variable in Python means setting a name to hold
a reference to some object.
Assignment creates references, not copies
You create a name the first time it appears on the left side
of an assignment expression:
x = 3
Multiple Assignment
You can also assign to multiple names at the same time.
>>> x, y = 2, 3
>>> x
2
>>> y
3
Naming Rules
Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob
Bob
_bob
_2_bob_
bob_2
BoB
Assignment (redundant)
Binding a variable in Python means setting a
name to hold a reference to some object.
Assignment creates references, not copies
Sequence types:
Tuples, Lists, and Strings
Sequence Types
1. Tuple
A simple immutable ordered sequence of items
Items can be of mixed types, including collection types
2. Strings
Immutable
Conceptually very much like a tuple
3. List
Mutable ordered sequence of items of mixed types
Similar Syntax
All three sequence types (tuples, strings, and
lists) share much of the same syntax and
functionality.
Key difference:
Tuples and strings are immutable
Lists are mutable
Sequence Types 1
Tuples are defined using parentheses (and commas).
>>> tu = (23,
def )
= Hello World
= Hello World
=
This is a multi-line
that uses triple quotes.
).
Sequence Types 2
We can access individual members of a tuple, list, or string
using square bracket array notation.
Note that all are 0 based
>>> tu = (23, abc , 4.56, (2,3), def )
>>> tu[1]
# Second item in the tuple.
abc
>>> li = [ abc , 34, 4.34, 23]
>>> li[1]
# Second item in the list.
34
>>> st = Hello World
>>> st[1]
# Second character in string.
e
>>> t = (23,
def )
>>> t = (23,
def )
>>> t = (23,
def )
Omit the first index to make a copy starting from the beginning
of the container.
>>> t[:2]
(23, abc )
def )
def )
The in Operator
Boolean test whether a value is inside a container:
>>> t
>>> 3
False
>>> 4
True
>>> 4
False
= [1, 2, 4, 5]
in t
in t
not in t
The + Operator
The + operator produces a new tuple, list, or string whose
value is the concatenation of its arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> Hello +
Hello World
World
The * Operator
The * operator produces a new tuple, list, or string that
repeats the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> Hello * 3
HelloHelloHello
Mutability:
Tuples vs. Lists
Tuples: Immutable
>>> t = (23, abc , 4.56, (2,3),
>>> t[2] = 3.14
def )
def )
Lists: Mutable
>>>
>>>
>>>
[
a ]
Confusing:
Extend takes a list as an argument.
Append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, i , 3, 4, 5, a , 9, 8, 7, [10, 11, 12]]
b ,
c ,
b ]
>>> li.index( b )
1
>>> li.count( b )
2
# number of occurrences
>>> li.remove( b )
>>> li
[ a , c , b ]
>>> li.sort()
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Why??
x = 3
First, an integer 3 is created and stored in memory
A name x is created
An reference to the memory location storing the 3 is then
assigned to the name x
So: When we say that the value of x is 3
we mean that x now refers to the integer 3
Name: x
Ref: <address1>
Type: Integer
Data: 3
name list
memory
Name: x
Ref: <address1>
Type: Integer
Data: 3
>>> x = x + 1
>>> x = x + 1
Name: x
Ref: <address1>
Type: Integer
Data: 3
Type: Integer
Data: 4
>>> x = x + 1
Name: x
Ref: <address1>
Type: Integer
Data: 3
Type: Integer
Data: 4
>>> x = x + 1
Assignment 1
So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
#
#
#
#
Creates 3, name
Creates name y,
Creates ref for
No effect on x,
x refers to 3
refers to 3.
4. Changes y.
still ref 3.
Assignment 1
So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
#
#
#
#
Creates 3, name
Creates name y,
Creates ref for
No effect on x,
Name: x
Ref: <address1>
x refers to 3
refers to 3.
4. Changes y.
still ref 3.
Type: Integer
Data: 3
Assignment 1
So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
#
#
#
#
Creates 3, name
Creates name y,
Creates ref for
No effect on x,
Name: x
Ref: <address1>
Name: y
Ref: <address1>
x refers to 3
refers to 3.
4. Changes y.
still ref 3.
Type: Integer
Data: 3
Assignment 1
So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
#
#
#
#
Creates 3, name
Creates name y,
Creates ref for
No effect on x,
Name: x
Ref: <address1>
Name: y
Ref: <address1>
x refers to 3
refers to 3.
4. Changes y.
still ref 3.
Type: Integer
Data: 3
Type: Integer
Data: 4
Assignment 1
So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
#
#
#
#
Creates 3, name
Creates name y,
Creates ref for
No effect on x,
Name: x
Ref: <address1>
Name: y
Ref: <address2>
x refers to 3
refers to 3.
4. Changes y.
still ref 3.
Type: Integer
Data: 3
Type: Integer
Data: 4
Assignment 1
So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
#
#
#
#
Creates 3, name
Creates name y,
Creates ref for
No effect on x,
Name: x
Ref: <address1>
Name: y
Ref: <address2>
x refers to 3
refers to 3.
4. Changes y.
still ref 3.
Type: Integer
Data: 3
Type: Integer
Data: 4
Assignment 2
For other data types (lists, dictionaries, user-defined types),
assignment works differently.
immutable
>>>
>>>
>>>
>>>
3
x = 3
y = x
y = 4
print x
mutable
x = some mutable object
y = x
make a change to y
look at x
x will be changed as well
a
b=a
b
a
a.append(4)
b
>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> print b
[1, 2, 3, 4]
Dictionaries
pswd :1234}
>>> d[ user ]
bozo
>>> d[ pswd ]
1234
>>> d[ bozo ]
Traceback (innermost last):
File <interactive input>
KeyError: bozo
line 1, in ?
Updating Dictionaries
>>> d = { user : bozo ,
pswd :1234}
>>> d[ id ] = 45
>>> d
{ user : clown , id :45,
pswd :1234}
p :1234,
i :34}
# Remove one.
>>> d.clear()
>>> d
{}
# Remove all.
p :1234,
i :34}
>>> d.keys()
[ user , p ,
# List of keys.
i ]
>>> d.values()
[ bozo , 1234, 34]
# List of values.
>>> d.items()
# List of item tuples.
[( user , bozo ), ( p ,1234), ( i ,34)]
Functions in Python
Defining Functions
Function definition begins with def.
def get_final_answer(filename):
Documentation String
line1
line2
return total_counter
The indentation matters
First line with less
indentation is considered to be
outside of the function definition.
Colon.
Dynamic Typing
Strong Typing
So, for example, you can t just append an integer to a string. You
must first convert the integer to a string itself.
x = the answer is
# Decides x is bound to a string.
y = 23
# Decides y is bound to an integer.
print x + y
# Python will complain about this.
Calling a Function
The syntax for a function call is:
>>> def myfun(x, y):
return x * y
>>> myfun(3, 4)
12
Arguments to function
Return values of functions
Assigned to variables
Parts of tuples, lists, etc
Logical Expressions
a and b
a or b
not a
X or Y or Z
If all are false, returns value of Z.
Otherwise, returns value of first true sub-expression.
But if the value of expr1 is ever False, the trick doesn t work.
Avoid (hard to debug), but you may see it in the code.
Made unnecessary by conditional expressions in Python 2.5
(see next slide)
Suggested use:
x = (true_value if condition else false_value)
Control of Flow
Control of Flow
There are several Python expressions that control
the flow of a program. All of them make use of
Boolean conditional tests.
if Statements
while Loops
assert Statements
if Statements
if x == 3:
print X equals 3.
elif x == 2:
print X equals 2.
else:
print X equals something else.
print This is outside the if .
while Loops
x = 3
while x < 10:
x = x + 1
print Still in the loop.
print Outside of the loop.
assert
An assert statement will check to make sure that
something is true during the course of a program.
If the condition if false, the program stops.
assert(number_of_players < 5)
List Comprehensions
A powerful feature of the Python language.
Generate a new list by applying a function to every member
of an original list.
Python programmers use list comprehensions extensively.
You ll see many of them in real code.
Note: Non-standard
colors on next several
slides to help clarify
the list comprehension
syntax.
It then collects these new values into a list which is the return
value of the list comprehension.
For Loops
For Loops 1
Note: Nonstandard colors
on these slides.
For Loops 2
for <item> in <collection>:
<statements>
Lambda Notation
>>> applier(lambda z: z * 4, 7)
28
Empty Containers 1
Assignment creates a name, if it didn t exist already.
x = 3 Creates name x of type integer.
Assignment is also what creates named references to
containers.
>>> d = { a :3, b :4}
We can also create empty containers:
>>> li = []
Note: an empty container
>>> tu = ()
is logically equivalent to
>>> di = {}
Empty Containers 2
Why create a named reference to empty container?
To initialize an empty list, for example, before using append.
This would cause an unknown name error a named reference to
the right data type wasn t created first
>>> g.append(3)
Python complains here about the unknown name g !
>>> g = []
>>> g.append(3)
>>> g
[3]
String Operations
String Operations
A number of methods for the string class perform useful
formatting operations:
>>> hello .upper()
HELLO
%s xyz %d
( abc , 34)
abc
>>> print
abc def
print
abc ,
abc ,
def
String Conversions
def ,
ghi ] )
Note: Non-standard
colors on this slide
to help clarify the
string syntax.
+ str(2)
import
import somefile
Everything in somefile.py gets imported.
To refer to something in the file, append the text somefile. to
the front of its name:
somefile.className.method(abc)
somefile.myFunction(34)
from import *
from somefile import *
Everything in somefile.py gets imported
To refer to anything in the module, just use its name. Everything
in the module is now in the current namespace.
Caveat! Using this import command can easily overwrite the
definition of an existing function or variable!
className.method(abc)
myFunction(34)
from import
from somefile import className
Only the item className in somefile.py gets imported.
After importing className, you can just use it without a module
prefix. Its brought into the current namespace.
Caveat! This will overwrite the definition of this particular name if
it is already defined in the current namespace!
className.method(abc)
myFunction(34)
Maxint
Module: os
Module: os.path
- OS specific code.
- Directory processing.
- Mathematical code.
Exponents
sqrt
Module: Random
Randrange
Uniform
Choice
Shuffle
It s all objects
Everything in Python is really an object.
We ve seen hints of this already
hello .upper()
list3.append( a )
dict2.keys()
These look like Java or C++ method calls.
New object classes can easily be defined in addition to these
built-in data-types.
Defining a Class
A class is a special data type which defines how
to build a certain kind of object.
The class also stores some data items that are shared by all
the instances of this class.
Instances are objects that are created which follow the
definition given inside of the class.
Methods in Classes
Define a method in a class by including function
definitions within the scope of the class block.
There must be a special first argument self in all method
definitions which gets bound to the calling instance
There is usually a special method called __init__ in most
classes
We ll talk about both later
Instantiating Objects
There is no new keyword as in Java.
Merely use the class name with () notation and
assign the result to a variable.
__init__ serves as a constructor for the class.
Usually does some initialization work.
The arguments passed to the class name are
given to its __init__() method.
So, the __init__ method for student is passed Bob and 21
here and the new class instance is bound to b:
Constructor: __init__
An __init__ method can take any number of
arguments.
Like other functions or methods, the arguments can be
defined with default values, making them optional to the
caller.
Self
The first argument of every method is a reference to the
current instance of the class.
By convention, we name this argument self.
Self
Although you must specify self explicitly when
defining the method, you don t include it when
calling the method.
Python passes it for you automatically.
Defining a method:
Calling a method:
>>> x.set_age(23)
Definition of student
class student:
A class representing a student.
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
# Access an attribute.
# Access a method.
getattr(object_instance, string)
>>> f = student( Bob Smith , 23)
>>> getattr(f,
Bob Smith
full_name )
get_age )()
hasattr(object_instance,string)
full_name )
>>> hasattr(f,
True
get_age )
>>> hasattr(f,
False
get_birthday )
Attributes
Class attributes
Data Attributes
Data attributes are created and initialized by an __init__
() method.
Simply assigning to a name creates the attribute.
Inside the class, refer to data attributes using self
for example, self.full_name
class teacher:
A class representing teachers.
def __init__(self,n):
self.full_name = n
def print_name(self):
print self.full_name
Class Attributes
Because all instances of a class share one copy of a class
attribute:
when any instance changes it, the value is changed for all instances.
Since there is one of these attributes per class and not one per
instance, they are accessed using a different notation:
Access class attributes using self.__class__.name notation.
class sample:
x = 23
def increment(self):
self.__class__.x += 1
>>> a = sample()
>>> a.increment()
>>> a.__class__.x
24
class counter:
overall_total = 0
# class attribute
def __init__(self):
self.my_total = 0
# data attribute
def increment(self):
counter.overall_total = \
counter.overall_total + 1
self.my_total = \
self.my_total + 1
>>>
>>>
>>>
>>>
>>>
>>>
1
>>>
3
>>>
2
>>>
3
a = counter()
b = counter()
a.increment()
b.increment()
b.increment()
a.my_total
a.__class__.overall_total
b.my_total
b.__class__.overall_total
Inheritance
Subclasses
A class can extend the definition of another class
Allows use (or extension ) of methods and attributes already
defined in the previous one.
New class: subclass. Original: parent, ancestor or superclass
Redefining Methods
To redefine a method of the parent class, include a new
definition using the same name in the subclass.
The old code won t get executed.
Extending __init__
Same as for redefining any other method
Commonly, the ancestor s __init__ method is executed in
addition to new commands.
You ll often see something like this in the __init__ method of
subclasses:
parentClass.__init__(self, x, y)
where parentClass is the name of the parent s class.
Special Built-In
Methods and Attributes
Special Methods
For example, the method __repr__ exists for all classes,
and you can always redefine it.
The definition of this method specifies how to turn an
instance of the class into a string.
print f sometimes calls f.__repr__() to produce a string for
object f.
If you type f at the prompt and hit ENTER, then you are also
calling __repr__ to determine what to display to the user as
output.
+ self.full_name
Special Methods
You can redefine these as well:
__init__
__cmp__
__len__
__copy__
Useful:
dir(x) returns a list of all methods and attributes
defined for object x
Exception Handling
Errors are a kind of object in Python.
More specific kinds of errors are subclasses of the general Error
class.
Try
Except
Finally
Catch
See
Section 6.8 of the Python reference manual (click
here)
Finally
pass
It does absolutely nothing.
Just holds the place of where something should go
syntactically. Programmers like to use it to waste time in
some code, or to hold the place where they would like put
some real code at a later time.
for i in range(1000):
pass
Like a no-op in assembly code, or a set of empty braces {}
in C++ or Java.
Substitutions
E.g. replace all instances of l with s.
Creates an output string (doesn t modify input)
>>> re.sub( l , s , sent)
cosoursess green ideas sseep furioussy
Work on substrings (NB not words)
>>> re.sub( green , red , sent)
colourless red ideas sleep furiously
Structured Results
Select a sub-part to be returned
e.g. non-vowel characters which appear before a
vowel:
>>> re.findall( ([^aeiou])[aeiou] , sent)
[ c , l , l , r ,
, d , l , f , r ]
generate tuples, for later tabulation
>>> re.findall( ([^aeiou])([aeiou]) , sent)
[( c , o ), ( l , o ), ( l , e ), ( r , e ),
Penn Treebank