Transcript Python

Python
A Crash Course
Python?
Isn’t that a snake?
Yes, but it is also a ...
... general-purpose open source computer
programming language, optimized for quality,
productivity, portability, and integration. It is used
by hundreds of thousands of developers around
the world, in areas such as Internet scripting,
systems programming, user interfaces, product
customization, and more.
From Programming Python 2nd Ed.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
No compile of link steps
No type declarations
Automatic memory management
High-level datatypes and operation
Object-oriented programming
Embedding and extending in C/C++
Classes, modules, exceptions
A simple, clear syntax and design
Universal “first-class” object model
Interactive , dynamic nature
Access to interpreter information
Wide interpreter portability
Large collection of libraries & tools
System calls
What does it look like?
foo = 10
bar = “foo”
foo2, bar2 = foo, bar
if x < 5 or (x > 10 and x < 20):
print "The value is OK."
if x < 5 or 10 < x < 20:
print "The value is OK."
for i in [1,2,3,4,5]:
print "This is iteration number", i
for j in range(5):
print “This is iteration number”, j+1
x = 10
while x >= 0:
print "x is still not negative."
x = x-1
Calculator Basics
Numbers
x,y = 10, 5
z = x + y
x,y = 10.2, 4.8
z = x + y
x
y
z
a
=
=
=
=
10.2 + 4.8j
complex(10,4)
x.real
y.imag
Strings
u“spam eggs” #unicode
d = r‘spam eggs’ #raw
l = len(d)
“””
spam
eggs
”””
s = “spam” + “eggs”
varSpam = s[0:4]
Lists
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>>
>>>
>>>
3
>>>
[2,
>>>
2
>>>
>>>
[1,
>>>
[2,
q = [2, 3]
p = [1, q, 4]
len(p)
p[1]
3]
p[1][0]
p[1].append('xtra')
p
[2, 3, 'xtra'], 4]
q
3, 'xtra']
Dictionaries
>>>d2 = {‘spam’:2, ‘ham’:1, ‘eggs’:3}
>>>d2[‘ham’]
2
>>>len(d2)
3
In Python false is [ ], 0, “”,
>>>d2.has_key(‘spam’)
None
1
true is everything else
>>>d2.keys()
[‘spam’,’ham’,’eggs’]
>>>del d2[‘ham’]
1
>>>len(d2)
2
Tuples
>>> a = ("foo",10,5+6j)
>>> a
('foo', 10, (5+6j))
>>> a[0]
'foo‘
>>> del a[1]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item deletion
>>>
Functions
def fib(n):
# write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def foo(n):
return lambda x: x+ n
Modules
- files that have Python functions and statements
- can by run as a script or imported
- .py extension
- module namespace
- import sys
- from sys import *
- __name__ is the name of the module
- if running as a script it is ‘__main__’
Files
import sys
#built atop C i/o
myFile = open(”file.txt”, ‘r’)
# ‘r’ read
# ‘w’ write
# ‘a’ append
a = myFile.readline()
#go over a list of strings returned by readlines()
for i in myFile.readlines():
sys.stdout.write(i)
#tell & seek are also methods
#optional if exiting app since GC will close it then
myFile.close()
Exceptions
import string, sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(string.strip(s))
except IOError, (errno, strerror): # exception w/ arguments
print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except: #default
print "Unexpected error:", sys.exc_info()[0]
raise #throw
finally:
pass
try:
raise NameError, 'HiThere'
except NameError:
print 'An exception flew by!'
raise
#User defined exceptions extend the Exception class
Classes
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
Boost.python
Following C/C++ tradition, let's start with the "hello, world". A C++ Function:
char const *greet ()
{return "hello, world" ;}
can be exposed to Python by writing a Boost.Python wrapper:
#include <boost/python.hpp >
using namespace boost::python ;
BOOST_PYTHON_MODULE (hello ){
def ("greet" ,greet );
}
That's it. We're done. We can now build this as a shared library. The resulting DLL is now
visible to Python. Here's a sample Python session:
>>> import hello
>>> print hello.greet()
hello ,world
Jython
C:\jython>jython
Jython 2.0 on java1.2.1
Type "copyright", "credits" or "license" for more information.
>>> from java.util import Random
>>> r = Random()
>>> r.nextInt()
-790940041
>>> for i in range(5):
...
print r.nextDouble()
...
0.23347681506123852
0.8526595592189546
0.3647833839988137
0.3384865260567278
0.5514469740469587
>>>
References
Lutz, Mark. Programming Python, 2nd Ed.
(Safari online through UW Libraries)
Lutz, Mark & Ascher, David. Learning Python
(In ACM Library in 326)
www.jython.org
www.python.org
http://www.boost.org/libs/python/doc/index.htm
l