Python I: Some Material Adapted From Upenn Cmpe391 Slides and Other Sources
Python I: Some Material Adapted From Upenn Cmpe391 Slides and Other Sources
History
Installing & Running Python
Names & Assignment
Sequences types: Lists, Tuples, and
Strings
Mutability
Understanding Reference Semantics in
Python
Brief History of Python
Invented in the Netherlands, early 90s
by Guido van Rossum
Named after Monty Python
Open sourced from the beginning
Considered a scripting language, but is
much more
Scalable, object oriented and functional
from the beginning
Used by Google from the beginning
Pythons Benevolent Dictator For Life
Python is an experiment in
how much freedom program-
mers need. Too much freedom
and nobody can read another's
code; too little and expressive-
ness is endangered.
- Guido van Rossum
http://docs.python.org/
The Python tutorial is good!
Running
Python
The Python Interpreter
Typical Python implementations offer
both an interpreter and compiler
Interactive interface to Python with a
read-eval-print loop
[finin@linux2 ~]$ python
Python 2.4.3 (#1, Jan 14 2008, 18:32:40)
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>>
Installing
Python is pre-installed on most Unix systems,
including Linux and MAC OS X
The pre-installed version may not be the most
recent one (2.6 as of Nov 2008)
Download from http://python.org/download/
Python comes with a large library of standard
modules
There are several options for an IDE
IDLE works well with Windows
Emacs with python-mode or your favorite text editor
Eclipse with Pydev (http://pydev.sourceforge.net/)
IDLE Development Environment
IDLE is an Integrated DeveLopment Environ-
ment for Python, typically used on Windows
Multi-window text editor with syntax
highlighting, auto-completion, smart indent
and other.
Python shell with syntax highlighting.
Integrated debugger
with stepping, persis-
tent breakpoints,
and call stack visi-
bility
Editing Python in Emacs
Emacs python-mode has good support for editing
Python, enabled enabled by default for .py files
Features: completion, symbol help, eldoc, and inferior
interpreter shell, etc.
Running Interactively on UNIX
On Unix
% python
>>> 3+3
6
Python prompts with >>>.
To exit Python (not Idle):
In Unix, type CONTROL-D
In Windows, type CONTROL-Z + <Enter>
Evaluate exit()
Running Programs on UNIX
Call python program via the python interpreter
% python fact.py
Make a python file directly executable by
Adding the appropriate path to your python
interpreter as the first line of your file
#!/usr/bin/python
Making the file executable
% chmod a+x fact.py
Invoking file from Unix command line
% fact.py
Example script: fact.py
#! /usr/bin/python
def fact(x):
"""Returns the factorial of its argument, assumed to be a posint"""
if x == 0:
return 1
return x * fact(x - 1)
print
print N fact(N)
print "---------"
for n in range(10):
print n, fact(n)
Python Scripts
When you call a python program from the
command line the interpreter evaluates each
expression in the file
Familiar mechanisms are used to provide
command line arguments and/or redirect
input and output
Python also has mechanisms to allow a
python program to act both as a script and as
a module to be imported and used by another
python program
Example of a Script
#! /usr/bin/python
""" reads text from standard input and outputs any email
addresses it finds, one to a line.
"""
import re
from sys import stdin
# a regular expression ~ for a valid email address
pat = re.compile(r'[-\w][-.\w]*@[-\w][-\w.]+[a-zA-Z]{2,4}')
for line in stdin.readlines():
for address in pat.findall(line):
print address
results
pat = re.compile(r'[-\w][-.\w]*@[-\w][-\w.]+[a-zA-Z]{2,4})
# found is an initially empty set (a list w/o duplicates)
found = set()
for line in stdin.readlines():
for address in pat.findall(line):
found.add(address)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> Hello * 3
HelloHelloHello
Mutability:
Tuples vs. Lists
Lists are mutable
>>> li.insert(2, i)
>>>li
[1, 11, i, 3, 4, 5, a]
The extend method vs +
+ creates a fresh list with a new memory ref
extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, i, 3, 4, 5, a, 9, 8, 7]
Potentially 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]]
Operations on Lists Only
Lists have many methods, including index,
count, remove, reverse, sort
>>> li = [a, b, c, b]
>>> li.index(b) # index of 1st occurrence
1
>>> li.count(b) # number of occurrences
2
>>> li.remove(b) # remove 1st occurrence
>>> li
[a, c, b]
Operations on Lists Only
>>> li = [5, 2, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Tuple details
The comma is the tuple creation operator, not parens
>>> 1,
(1,)
Type: Integer
Name: x Data: 3
Ref: <address1>
>>> x = x + 1
Understanding Reference Semantics
When we increment x, then what happening is:
1. The reference of name x is looked up.
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new
data element 4 which is assigned to a fresh
memory location with a new reference
Type: Integer
Name: x Data: 3
Ref: <address1>
Type: Integer
Data: 4
>>> x = x + 1
Understanding Reference Semantics
When we increment x, then what happening is:
1. The reference of name x is looked up.
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new
data element 4 which is assigned to a fresh
memory location with a new reference
4. The name x is changed to point to new ref
Type: Integer
Name: x Data: 3
Ref: <address1>
Type: Integer
Data: 4
>>> x = x + 1
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Ref: <address2>
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Type: Integer
Ref: <address2>
Data: 4
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Type: Integer
Ref: <address2>
Data: 4
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Type: Integer
Ref: <address2>
Data: 4
Assignment
So, for simple built-in datatypes (integers, floats,
strings) assignment behaves as expected
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3
>>> y = 4 # Creates ref for 4. Changes y
>>> print x # No effect on x, still ref 3
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Type: Integer
Ref: <address2>
Data: 4
Assignment & mutable objects
For other data types (lists, dictionaries, user-
defined types), assignment works differently
These datatypes are mutable
Change occur in place
We dont copy them into a new memory address
each time
If we type y=x and then modify y, both x and y are
changed
immutable mutable
>>> x = 3 x = some mutable object
>>> y = x y = x
>>> y = 4 make a change to y
>>> print x look at x
3 x will be changed as
well
Why? Changing a Shared List
a = [1, 2, 3] a 1 2 3
a
b=a 1 2 3
b
a
a.append(4) 1 2 3 4
b
Surprising example surprising no more