Python
Raje Ramrao Mahavidyalaya, Jath.
Department of B.C.A.
Name:-Miss Balikai J.I.
*
Introduction
*
Python philosophy
*
Python features
*
no compiling or linking | rapid development cycle |
no type declarations | simpler, shorter, more flexible |
automatic memory management | garbage collection |
high-level data types and operations | fast development |
object-oriented programming | code structuring and reuse, C++ |
embedding and extending in C | mixed language systems |
classes, modules, exceptions | "programming-in-the-large" support |
dynamic loading of C modules | simplified extensions, smaller binaries |
dynamic reloading of C modules | programs can be modified without stopping |
Lutz, Programming Python
Python features
*
universal "first-class" object model | fewer restrictions and rules |
run-time program construction | handles unforeseen needs, end-user coding |
interactive, dynamic nature | incremental development and testing |
access to interpreter information | metaprogramming, introspective objects |
wide portability | cross-platform programming without ports |
compilation to portable byte-code | execution speed, protecting source code |
built-in interfaces to external services | system tools, GUIs, persistence, databases, etc. |
Lutz, Programming Python
Python
*
Advanced Programming
Spring 2002
Uses of Python
*
What not to use Python (and kin) for
*
Using python
Python 1.6 (#1, Sep 24 2000, 20:40:45) [GCC 2.95.1 19990816 (release)] on sunos5
Copyright (c) 1995-2000 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>>
*
Python structure
*
First example
#!/usr/local/bin/python
# import systems module
import sys
marker = '::::::'
for name in sys.argv[1:]:
input = open(name, 'r')
print marker + name
print input.read()
*
Basic operations
*
String operations
*
Lists
*
Basic programming
a,b = 0, 1
# non-zero = true
while b < 10:
# formatted output, without \n
print b,
# multiple assignment
a,b = b, a+b
*
Control flow: if
x = int(raw_input("Please enter #:"))
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
*
Control flow: for
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
print i, a[i]
*
Loops: break, continue, else
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is prime'
*
Do nothing
while 1:
pass
*
Defining functions
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
>>> fib(2000)
*
Functions: default argument values
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no'): return 0
retries = retries - 1
if retries < 0: raise IOError, 'refusenik error'
print complaint
>>> ask_ok('Really?')
*
Keyword arguments
def parrot(voltage, state='a stiff', action='voom', type='Norwegian blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "Lovely plumage, the ", type
print "-- It's", state, "!"
parrot(1000)
parrot(action='VOOOM', voltage=100000)
*
Lambda forms
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
f(1)
*
List methods
*
List methods
*
Functional programming tools
def f(x): return x%2 != 0 and x%3 0
filter(f, range(2,25))
*
List comprehensions (2.0)
>>> vec = [2,4,6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [{x: x**2} for x in vec}
[{2: 4}, {4: 16}, {6: 36}]
*
List comprehensions
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [x+y for x in vec1 and y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8,12,-54]
*
List comprehensions
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
*
del – removing list items
>>> a = [-1,1,66.6,333,333,1234.5]
>>> del a[0]
>>> a
[1,66.6,333,333,1234.5]
>>> del a[2:4]
>>> a
[1,66.6,1234.5]
*
Tuples and sequences
>>> t = 123, 543, 'bar'
>>> t[0]
123
>>> t
(123, 543, 'bar')
*
Advanced Programming
Spring 2002
Tuples
>>> u = t, (1,2)
>>> u
((123, 542, 'bar'), (1,2))
*
Tuples
>>> empty = ()
>>> len(empty)
0
>>> singleton = 'foo',
*
Tuples
>>> t = 123, 543, 'bar'
>>> x, y, z = t
>>> x
123
*
Dictionaries
>>> tel = {'hgs' : 7042, 'lennox': 7018}
>>> tel['cs'] = 7000
>>> tel
*
Dictionaries
>>> del tel['foo']
>>> tel.keys()
['cs', 'lennox', 'hgs']
>>> tel.has_key('foo')
0
*
Conditions
>>> if (4 in vec):
... print '4 is'
a < b == c
*
Conditions
>>> s1,s2,s3='', 'foo', 'bar'
>>> non_null = s1 or s2 or s3
>>> non_null
foo
*
Comparing sequences
*
Comparing sequences
(1,2,3) < (1,2,4)
[1,2,3] < [1,2,4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1,2,3) == (1.0,2.0,3.0)
(1,2) < (1,2,-1)
*
Modules
def fib(n): # write Fib. series up to n
...
def fib2(n): # return Fib. series up to n
*
Modules
import fibo
>>> fibo.fib(1000)
>>> fibo.__name__
'fibo'
>>> fib = fibo.fib
>>> fib(500)
*
Modules
>>> from fibo import fib, fib2
>>> fib(500)
>>> from fibo import *
*
Module search path
>>> import sys
>>> sys.path
['', 'C:\\PROGRA~1\\Python2.2', 'C:\\Program Files\\Python2.2\\DLLs', 'C:\\Program Files\\Python2.2\\lib', 'C:\\Program Files\\Python2.2\\lib\\lib-tk', 'C:\\Program Files\\Python2.2', 'C:\\Program Files\\Python2.2\\lib\\site-packages']
*
Compiled Python files
*
Standard modules
>>> import sys
>>> sys.p1
'>>> '
>>> sys.p2
'... '
>>> sys.path.append('/some/directory')
*
Module listing
>>> dir(fibo)
['___name___', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__st
din__', '__stdout__', '_getframe', 'argv', 'builtin_module_names', 'byteorder',
'copyright', 'displayhook', 'dllhandle', 'exc_info', 'exc_type', 'excepthook', '
exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getrecursionlimit', '
getrefcount', 'hexversion', 'last_type', 'last_value', 'maxint', 'maxunicode', '
modules', 'path', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setpr
ofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version',
'version_info', 'warnoptions', 'winver']
*
Classes
*
Classes
*
Class definitions
Class ClassName:
<statement-1>
...
<statement-N>
*
Namespaces
*
Namespaces
*
Class objects
class MyClass:
"A simple example class"
i = 123
def f(self):
return 'hello world'
>>> MyClass.i
123
Advanced Programming
Spring 2002
Class objects
>>> x = MyClass()
>>> x.f()
'hello world'
def __init__(self,realpart,imagpart):
self.r = realpart
self.i = imagpart
*
Instance objects
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
*
Method objects
x.f()
xf = x.f
while 1:
print xf()
*
Notes on classes
*
Another example
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)
*
Another example, cont'd.
>>> from bag import *
>>> l = Bag()
>>> l.add('first')
>>> l.add('second')
>>> l.data
['first', 'second']
*
Inheritance
class DerivedClassName(BaseClassName)
<statement-1>
...
<statement-N>
*
Multiple inheritance
class DerivedClass(Base1,Base2,Base3):
<statement>
*
Private variables
*
~ C structs
class Employee:
pass
john = Employee()
john.name = 'John Doe'
john.dept = 'CS'
john.salary = 1000
*
Exceptions
while 1 print 'Hello World'
File "<stdin>", line 1
while 1 print 'Hello World'
^
SyntaxError: invalid syntax
*
Handling exceptions
while 1:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Not a valid number"
*
Handling exceptions
import sys
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'lines:', len(f.readlines())
f.close
*
Language comparison
*
| | Tcl | Perl | Python | JavaScript | Visual Basic |
Speed | development | ✔ | ✔ | ✔ | ✔ | ✔ |
| regexp | ✔ | ✔ | ✔ | | |
breadth | extensible | ✔ | | ✔ | | ✔ |
| embeddable | ✔ | | ✔ | | |
| easy GUI | ✔ | | ✔ (Tk) | | ✔ |
| net/web | ✔ | ✔ | ✔ | ✔ | ✔ |
enterprise | cross-platform | ✔ | ✔ | ✔ | ✔ | |
| I18N | ✔ | | ✔ | ✔ | ✔ |
| thread-safe | ✔ | | ✔ | | ✔ |
| database access | ✔ | ✔ | ✔ | ✔ | ✔ |