Professional Documents
Culture Documents
Swaroop, C. H.
www.byteofpython.info
Python
..................................................................................................................................................1
...................................................................................................................................1
...................................................................................................................................1
...........................................................................................................................2
.......................................................................................................................................2
..............................................................................................................................................2
...................................................................................................................2
1 ....................................................................................................................................4
..............................................................................................................................................4
Python ...............................................................................................................................4
Perl ....................................................................................................................7
...................................................................................................................................7
2 Python ........................................................................................................................9
LinuxBSD .........................................................................................................................9
Windows ..........................................................................................................................10
............................................................................................................................................10
3 ......................................................................................................................11
............................................................................................................................................11
.............................................................................................................11
.........................................................................................................................12
.................................................................................................................................13
Python .................................................................................................................14
.....................................................................................................................................15
............................................................................................................................................16
4 ..........................................................................................................................17
.....................................................................................................................17
................................................................................................................................................17
.........................................................................................................................................17
............................................................................................................................................20
.............................................................................................................................20
.....................................................................................................................................21
............................................................................................................................................21
.........................................................................................................................22
............................................................................................................................................24
............................................................................................................................................25
5 ...............................................................................................................26
............................................................................................................................................26
.........................................................................................................................................26
.............................................................................................................................28
.........................................................................................................................................29
Python
............................................................................................................................................30
6 ..............................................................................................................................31
............................................................................................................................................31
if ..........................................................................................................................................31
while....................................................................................................................................34
for........................................................................................................................................36
break....................................................................................................................................37
continue...............................................................................................................................39
............................................................................................................................................40
7 ..................................................................................................................................41
............................................................................................................................................41
.....................................................................................................................................42
.....................................................................................................................................43
.................................................................................................................................45
.....................................................................................................................................47
return ...................................................................................................................................48
DocStrings...................................................................................................................................49
............................................................................................................................................51
8 ..................................................................................................................................52
............................................................................................................................................52
.pyc..................................................................................................................54
from..import ........................................................................................................................54
__name__ ........................................................................................................................54
.....................................................................................................................55
dir() .....................................................................................................................................57
............................................................................................................................................59
9 ..........................................................................................................................60
............................................................................................................................................60
............................................................................................................................................60
............................................................................................................................................63
............................................................................................................................................66
............................................................................................................................................68
............................................................................................................................................71
.....................................................................................................................72
............................................................................................................................................74
10 Python ............................................................................75
............................................................................................................................................75
.....................................................................................................................................75
.............................................................................................................................86
............................................................................................................................................86
11 .............................................................................................................87
............................................................................................................................................87
self...............................................................................................................................................87
................................................................................................................................................88
II
Python
.................................................................................................................................89
__init__ ...............................................................................................................................90
.........................................................................................................................91
............................................................................................................................................95
............................................................................................................................................98
12 / .......................................................................................................................99
............................................................................................................................................99
.......................................................................................................................................101
..........................................................................................................................................102
13 ..............................................................................................................................103
..........................................................................................................................................103
try..except..................................................................................................................................103
...................................................................................................................................105
try..finally..................................................................................................................................107
..........................................................................................................................................108
14 Python ..............................................................................................................109
..........................................................................................................................................109
sys .....................................................................................................................................109
os .......................................................................................................................................112
..........................................................................................................................................113
15 Python ......................................................................................................114
...............................................................................................................................114
...................................................................................................................................115
...................................................................................................................................115
.......................................................................................................116
lambda...............................................................................................................................117
execeval.........................................................................................................................118
assert .................................................................................................................................118
repr ....................................................................................................................................118
..........................................................................................................................................119
16 .......................................................................................................120
...................................................................................................................................120
...........................................................................................................................121
..........................................................................................................................................122
A /FLOSS ....................................................................................123
B ..........................................................................................................................126
..............................................................................................................................................126
......................................................................................................................................126
......................................................................................................................................126
......................................................................................................................127
C ..........................................................................................................................128
.......................................................................................................................................128
.......................................................................................................................................129
III
Python
1.20
A Byte of Python
Copyright 2003-2005 Swaroop C H
Python
Python "A Byte of Python"
2005
--
Python
Python
Python
Python
Python
Python Python
Python
Python
Python
PythonPerlQt
Eric S. RaymondPython
PyQtPerl-Qt
Python
Python
O'Reilly
Python
Python
Python
Python
Python
Python
wxPythonTwisted
Boa Constructor
www.byteofpython.info
--
swaroop@byteofpython.info
Python
C.A.R. Hoare
C.W. Wendte
Python
Python
Python
Python
Python
Python
Python
Python
Python Python
Python
Python
Python
Python
Python FLOSS/
FLOSS
Python
Python
Python
Python
Python
LinuxWindowsFreeBSDMacintoshSolarisOS/2
AmigaAROSAS/400BeOSOS/390z/OSPalm OSQNXVMSPsion
Acom RISC OSVxWorksPlayStationSharp ZaurusWindows CE
PocketPC
C C++ C C++
0 1
/
Python
Python
Python
Python Python
Python
Python
C++ Java Python
C C++ Python
Python C/C++
Python
CGIFTP
XMLXML-RPCHTMLWAV GUI
Tk Python
Python
wxPythonTwisted
Python
Python
Python
Perl
Perl
Perl
Perl
Perl
Yahoo Perl
Perl Python
Perl
Python
Perl Perl 6
PerlCPANPerl
Perl
PerlPython
Perlcomp.lang.pythonPerl
Python
ParrotPerl 6
PythonRubyPHPTcl
PythonPerlCPAN
Python
ESR Python
Python
Peter NorvigLispGoogle
Guido van RossumPythonGoogle
Google
Python
Python
2 Python
LinuxBSD
Linux Fedora Mandrake
BSD FreeBSD
Python
Linux Python shell
konsole gnome-terminal python -V
$ python -V
Python 2.3.4
$ shell
$
Python
$ python -V
bash: python: command not found
Python
Python
Fedora Linux
yumMandrake Linux urpmiDebian Linux apt-getFreeBSD
pkg_add
PC
Python
Python
Windows
WindowsPython.org/download
2.3.4 9.4MB
Windows
Windows Python
Windows Python
PATH
Windows 2000XP2003->->->
PATH
;C:\Python23 Python
Windows C:\AUTOEXEC.BAT
PATH=%PATH%;C:\Python23 Windows
NT AUTOEXEC.NT
Linux Python
Python Windows Python
Python
10
Python
11
Python
Python Python
print
Hello World
Python
Linux/BSD shell Ctrl-d
Windows Ctrl-z Enter
Python
Python
Python
Windows IDLEIDLE
IDLE
Notepad
IDLE VIM
Linux/FreeBSD
VIM Emacs
Python VIM
Kate
VIM Emacs
Python
PythonIDE
PythonIDE
PythonIDE
12
Python
Python
Hello World
Hello WorldHello World
Hello WorldSimon Cozens[1]
helloworld.py
3.2
#!/usr/bin/python
# Filename : helloworld.py
print 'Hello World'
code/helloworld.py
shellLinux DOS
python helloworld.py IDLE Edit->Run Script
Ctrl-F5
$ python helloworld.py
Hello World
Python
Python print Print
p P
13
Python
Python
#!Linux/Unix
python helloworld.py
6
Python Hello World
print Hello World
[1]
Perl6/ParrotPerl
Python
Linux/Unix Windows
chmod
14
Python
helloworld
./helloworld
PATH
PATH
PATH
$ echo $PATH
/opt/mono/bin/:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/ho
me/swaroop/bin
$ cp helloworld.py /home/swaroop/bin/helloworld
$ helloworld
Hello World
echo PATH $ shell
/home/swaroop/bin PATH
swaroop
PATH
PATH=$PATH:/home/swaroop/mydir /home/swaroop/mydir
PATH
cd Linux DOS
Python
Python
help
help(str) str str
15
Python
q
Python help()
help
print
PYTHONDOCS Linux/Unix env
$
env
PYTHONDOCS=/usr/share/doc/python-docs-2.3.4/html/
python
Python 2.3.4 (#1, Oct 26 2004, 16:42:40)
[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> help('print')
print Python
print
Fedora Core 3 Linux
Python Python
Python
16
Python
Hello World
Python
51.239.25e-3 'This
is a string'"It's a string!"
2
Python 4
(-5+4j)(2.3-4.6j)
Python
Python
'
17
Python
'Quote me on this'
"
'''"""
'
What's your name?
\'
'What\'s your name?'
18
Python
\\
r R
r"Newlines are indicated by \n"
Unicode
Unicode
Unicode
Python Unicode u
19
Python
Python
'What\'s' 'your name?'"What's your name?"
C/C++
Python char
Perl/PHP
'\\1' r'\1'
_
20
Python
0-9
myname myName
n N
i__my_namename_23 a1b2_c3
2thingsthis is spaced out my-name
Python
Python
Python
Python
1.
2.
3.
Python.py
4. python program.py IDLE
4.1
21
Python
# Filename : var.py
i=5
print i
i=i+1
print i
s = '''This is a multi-line string.
This is the second line.'''
print s
code/var.py
$ python var.py
5
6
This is a multi-line string.
This is the second line.
=
5 i
i 5 print
i
i 1 i 6
s
C/C++
22
Python
Python
Python
print 'Hello World'
Python
;
/
i=5
print i
i = 5;
print i;
i = 5; print i;
i = 5; print i
Python
s = 'This is a string. \
This continues the string.'
print s
23
Python
print \
i
print i
Python
i=5
print 'Value is', i # Error! Notice a single space at the start
of the line
print 'I repeat, the value is', i
24
Python
^
SyntaxError: invalid syntax
Python
25
Python
2 + 3
+
2 3
2 + 3 Python
>>> 2 + 3
5
>>> 3 * 5
15
>>>
5.1
3 + 5 8'a' + 'b''ab'
-5.2 50 - 24 26
2 * 3 6'la' * 3 'lalala'
26
Python
**
x y
3 ** 4 81 3 * 3 * 3 * 3
x y
4/3 1
4.0/3 4/3.0
1.3333333333333333
//
4 // 3.0 1.0
2 << 2 82
10
0 1
>>
11 >> 1 511
1011 1 101
5
&
5 & 3 1
5 | 3 7
5 ^ 3 6
x -(x+1)
~5 6
<<
x y
5 < 3 0 False 3 < 5
1 0
1 True
True False
3 < 5 < 7 True
>
5 > 3 True
False
<=
x y
x = 3; y = 6; x <= y True
>=
x y
x = 4; y = 3; x >= y True
==
x = 2; y = 2; x == y Truex = 'str';
y = 'stR'; x == y Falsex = 'str'; y
= 'str'; x == y True
!=
x = 2; y = 3; x != y True
not
x True False x
x = True; not y False
False True
and
y
y
False x False
<
x y
27
Python
or
2 + 3 * 4
Python
Python
Python
2 + (3 * 4) 2 + 3 * 4
2 + (3 + 4)
5.2
lambda
Lambda
or
and
not x
innot in
isis not
<<=>>=!=
==
|
&
<<>>
+-
*/%
28
Python
+x-x
~x
**
x.attribute
x[index]
x[index:index]
f(arguments...)
(experession,...)
[expression,...]
{key:datum,...}
'expression,...'
+-
(2 + 3) * 4
2 + 3 + 4 (2 + 3) + 4
a = b = c a = (b = c)
5.1
29
Python
#!/usr/bin/python
# Filename: expression.py
length = 5
breadth = 2
area = length * breadth
print 'Area is', area
print 'Perimeter is', 2 * (length + breadth)
code/expression.py
$ python expression.py
Area is 10
Perimeter is 14
Python
30
Python
Python
Python
iffor while
if
if if-
else- else
if
6.1 if
#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block starts
here
print "(but you do not win any prizes!)" # New block ends
here
elif guess < number:
31
Python
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done
$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done
number 23
raw_input()
32
Python
raw_input
raw_input int
guess int
Python
Python
if Python
elif if else-if
else if-elif-else
elif else
if if if
elif else if
if True:
print 'Yes, it is true'
Python if elif else
if
print 'Done'Python
C/C++
33
Python
C/C++
Pythonswitchif..elif..else
while
while while
while else
while
6.2 while
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'
34
Python
code/while.py
$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done
while
raw_input if while while
running True running True
while-
running while-
else-
while False else
while else
while
True False 1 0
1
else while
while
35
Python
C/C++
while else
for
for..in
for
6.3 for
#!/usr/bin/python
# Filename: for.py
for i in range(1, 5):
print i
else:
print 'The for loop is over'
$ python for.py
1
2
3
4
The for loop is over
range
36
Python
range
range(1,5)[1, 2, 3, 4]range
1 range
range(1,5,2)[1,3]range
C/C++/Java/C#
Python for C/C++ for C#
Python for C# foreach Java
Java 1.5 for (int i : IntArray)
C/C++ for (int i = 0; i < 5; i++) Python
for i in range(0,5)Python for
break
break False
break
6.4 break
37
Python
#!/usr/bin/python
# Filename: break.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
code/break.py
$ python break.py
Enter something : Programming is fun
Length of the string is 18
Enter something : When the work is done
Length of the string is 21
Enter something : if you wanna make your work also fun:
Length of the string is 37
Enter something :
use Python!
'quit'
len
break for
38
Python
G2 Python
G2 Python
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
continue
continue Python
continue
6.5 continue
#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'
# Do other kinds of processing here...
code/continue.py
39
Python
$ python continue.py
Enter something : a
Enter something : 12
Enter something : abc
Input is of sufficient length
Enter something : quit
3
len
3 continue
continue for
ifwhile for
break continue Python
40
Python
len range
def def
7.1
#!/usr/bin/python
# Filename: function1.py
def sayHello():
print 'Hello World!' # block belonging to the function
sayHello() # call the function
code/function1.py
$ python function1.py
Hello World!
41
Python
sayHello
7.2
#!/usr/bin/python
# Filename: func_param.py
def printMax(a, b):
if a > b:
print a, 'is maximum'
else:
print b, 'is maximum'
printMax(3, 4) # directly give literal values
x=5
y=7
printMax(x, y) # give variables as arguments
42
Python
code/func_param.py
$ python func_param.py
4 is maximum
7 is maximum
printMax a
b if..else
printMax
printMax(x, y) x a
y bprintMax
7.3
#!/usr/bin/python
# Filename: func_local.py
def func(x):
print 'x is', x
x=2
print 'Changed local x to', x
43
Python
x = 50
func(x)
print 'x is still', x
code/func_local.py
$ python func_local.py
x is 50
Changed local x to 2
x is still 50
x Python
2 xx
x x
print x
global
Python
global global
global
7.4 global
#!/usr/bin/python
# Filename: func_global.py
44
Python
def func():
global x
print 'x is', x
x=2
print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x
code/func_global.py
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2
global x x
x
global global x, y, z
45
Python
7.5
#!/usr/bin/python
# Filename: func_default.py
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)
code/func_default.py
$ python func_default.py
Hello
WorldWorldWorldWorldWorld
say
times 1
say
say 5
5
46
Python
def func(a,
b=5) def func(a=5, b)
7.6
#!/usr/bin/python
# Filename: func_key.py
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
code/func_key.py
47
Python
$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
func
func(3, 7) a 3 b 7
c 10
func(25, c=24) a 25
c 24 b 5
func(c=50, a=100)
a c a c
return
return
7.7
#!/usr/bin/python
# Filename: func_return.py
def maximum(x, y):
if x > y:
return x
48
Python
else:
return y
print maximum(2, 3)
code/func_return.py
$ python func_return.py
3
maximum
if..else
return return NoneNone Python
None
DocStrings
Python
docstrings DocStrings
49
Python
DocStrings
7.8 DocStrings
#!/usr/bin/python
# Filename: func_doc.py
def printMax(x, y):
'''Prints the maximum of two numbers.
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.
50
Python
DocStrings
__doc__printMax
Python
Python
Python
51
Python
.py
Python
sys
8.1 sys
#!/usr/bin/python
# Filename: using_sys.py
import sys
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
code/using_sys.py
Python
using_sys.py
we
are
arguments
The
PYTHONPATH
is
['/home/swaroop/byte/code',
'/usr/lib/python23.zip',
'/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload',
'/usr/lib/python2.3/site-packages',
'/usr/lib/python2.3/site-packages/gtk-2.0']
53
Python
.pyc
Python
.pyc
Python
Python.pyc
.pyc
from..import
argv sys.
from sys import argv sys
from sys import *
from..import import
__name__
54
Python
__name__
__name__
8.2 __name__
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
code/using_name.py
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
Python __name__'__main__'
55
Python
Python
.py
8.3
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
# End of mymodule.py
code/mymodule.py
Python
Python
sys.path
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version
code/mymodule_demo.py
56
Python
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
Python
Python
from..import
from..import
#!/usr/bin/python
# Filename: mymodule_demo2.py
from mymodule import sayhi, version
# Alternative:
# from mymodule import *
sayhi()
print 'Version', version
code/mymodule_demo2.py
mymodule_demo2.py mymodule_demo.py
dir()
dir
dir()
57
Python
dir
8.4 dir
$ python
>>> import sys
>>> dir(sys) # get list of attributes for sys module
['__displayhook__',
'__doc__',
'__excepthook__',
'__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names',
'byteorder',
'call_tracing',
'callstats',
'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',
'excepthook',
'exec_prefix',
'executable',
'exit',
'getcheckinterval',
'getdefaultencoding',
'getdlopenflags',
'getfilesystemencoding',
'getrecursionlimit',
'getrefcount',
'hexversion',
'maxint',
'maxunicode',
'meta_path','modules',
'path',
'path_hooks',
'path_importer_cache',
'platform',
'prefix',
'ps1',
'ps2',
'setcheckinterval',
'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin',
'stdout',
'version', 'version_info', 'warnoptions']
>>> dir() # get list of attributes for current module
['__builtins__', '__doc__', '__name__', 'sys']
>>>
>>> a = 5 # create a new variable 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # delete/remove a name
>>>
>>> dir()
58
Python
sys dir
dir
dir a
dir del
/ dir
del /
del a a
Python
59
Python
Python
list
Python
Python
i
5int i
help(int)
60
Python
/ mylist.field
9.1
#!/usr/bin/python
# Filename: using_list.py
61
Python
$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana',
'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango',
'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
shoplist shoplist
for..in
print print
append
sort
62
Python
del
del
del shoplist[0]Python 0
help(list)
9.2
#!/usr/bin/python
# Filename: using_tuple.py
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
code/using_tuple.py
$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
63
Python
zoolen
new_zoo
new_zoo[2]
new_zoo new_zoo[2][2] new_zoo
0 1
myempty
= ()
Python
2 singleton = (2 , )
Perl
Perl
Python
9.3
64
Python
#!/usr/bin/python
# Filename: print_tuple.py
age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name
code/print_tuple.py
$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?
print %
%s %d
%s name
%d age
Python
%s name
print
%s Python
65
Python
print %
dict /
9.4
#!/usr/bin/python
# Filename: using_dict.py
'Swaroop' : 'swaroopch@byteofpython.info',
'Larry'
: 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']
66
Python
$ python using_dict.py
Swaroop's address is swaroopch@byteofpython.info
67
Python
ab
/
/
Guido
del /
del
items /
in / dict
has_key help(dict) dict
9.5
68
Python
#!/usr/bin/python
# Filename: seq.py
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]
code/seq.py
$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
69
Python
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
Python
Python 0 shoplist[0]
shoplist[3] shoplist
shoplist[-1] shoplist[-2]
Python
Python
shoplist[1:3] 1 2 3
shoplist[:]
shoplist[:-1]
70
Python
Python
9.6
#!/usr/bin/python
# Filename: reference.py
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to
the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same
list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
71
Python
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
Perl
str
help(str)
72
Python
9.7
#!/usr/bin/python
# Filename: str_methods.py
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'
if 'a' in name:
print 'Yes, it contains the string "a"'
if name.find('war') != -1:
print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)
code/str_methods.py
$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
73
Python
startwith
in
find -1
str join
Python
Python
Python
74
Python
10 Python
Python
1.
2.
3. zip
4. zip
5. zip Linux/Unix
Windows Info-Zip
75
Python
10.1
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in
a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents',
r'D:\Work'] or something like that
Python
$ python backup_ver1.py
Successful backup to /mnt/e/backup/20041208073244.zip
os time source
target_dir zip
time.strftime().zip target_dir
time.strftime()%Y
%m 01 12
Python Python
Python print %
zip
zip_command shellLinux
DOS
zip -q zip -r
zip
-qr zip
join source
77
Python
os.system
shell 0
Windows
source target
Windows Windows \
Python
'C:\\Documents'
r'C:\Documents'
'C:\Documents'\D
Linux/Unix
10.2
78
Python
#!/usr/bin/python
# Filename: backup_ver2.py
import os
import time
# 1. The files and directories to be backed up are specified in
a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents',
r'D:\Work'] or something like that
Python
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
code/backup_ver2.py
$ python backup_ver2.py
Successfully created directory /mnt/e/backup/20041208
Successful backup to /mnt/e/backup/20041208/080020.zip
$ python backup_ver2.py
Successful backup to /mnt/e/backup/20041208/080428.zip
os.exists
os.mkdir
os.sep
LinuxUnix '/' Windows '\\' Mac OS ':' os.sep
zip
zip
10.3
80
Python
#!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
# 1. The files and directories to be backed up are specified in
a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents',
r'D:\Work'] or something like that
Python
$ python backup_ver3.py
File "backup_ver3.py", line 25
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax
Python Python
Python
Python
10.4
82
Python
#!/usr/bin/python
# Filename: backup_ver4.py
import os
import time
# 1. The files and directories to be backed up are specified in
a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents',
r'D:\Work'] or something like that
Python
$ python backup_ver4.py
Enter a comment --> added new examples
Successful
backup
to
/mnt/e/backup/20041208/082156_added_new_examples.zip
$ python backup_ver4.py
Enter a comment -->
Successful backup to /mnt/e/backup/20041208/082316.zip
raw_input len
zip .zip
84
Python
-v
-c
-v
-z gzip
-f
-X
*~~
zipfile tarfile
Python
os.system
os.system
85
Python
1.
2.
3.
4.
5.
6.
Python /
Python
86
Python
11
int int
C/C++/Java/C#
int C++Java
1.5 help(int)
C# Java 1.5
class
self
87
Python
Python
self
self
self IDE
C++/Java/C#
Python self C++ self JavaC# this
Python self
MyClass
MyObject MyObject.method(arg1, arg2)
Python MyClass.method(MyObject, arg1, arg2)
self
self
11.1
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass # An empty block
88
Python
p = Person()
print p
code/simplestclass.py
$ python simplestclass.py
<__main__.Person instance at 0xf6fcb18c>
class
pass
/
__main__Person
Python
/
self
11.2
#!/usr/bin/python
# Filename: method.py
class Person:
89
Python
def sayHi(self):
print 'Hello, how are you?'
p = Person()
p.sayHi()
# This short example can also be written as Person().sayHi()
code/method.py
$ python method.py
Hello, how are you?
self sayHi
self
__init__
Python __init__
__init__
__init__
11.3 __init__
#!/usr/bin/python
# Filename: class_init.py
class Person:
90
Python
This
short
example
can
also
be
written
as
Person('Swaroop').sayHi()
code/class_init.py
$ python class_init.py
Hello, my name is Swaroop
__init__
__init__
self.name sayHi
C++/Java/C#
__init__ C++C# Java constructor
91
Python
11.4
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying.'''
92
Python
'There
are
still
%d
people
left.'
Person.population
def sayHi(self):
'''Greeting by the person.
'We
have
%d
Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
swaroop.sayHi()
swaroop.howMany()
93
persons
here.'
Python
code/objvar.py
$ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
docstring
Person.__doc__ Person.sayHi.__doc__
94
Python
__init____del__
Person.population 1
__del__
del
C++/Java/C#
Python
__privatevarPython
/
Python
__del__ destructor
SchoolMember
95
Python
/ SchoolMember
SchoolMember
SchoolMember
SchoolMember Teacher
Student
11.5
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' % self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
96
Python
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
97
Python
__init__ self
Python
constructor
self
Python
Python
/ Python
98
Python
12 /
raw_input print
str
rjust help(str)
12.1
#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
99
Python
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
file
'r''w''a'
help(file)
file write
close
readline
100
Python
print
close
poem.txt
Python pickle
Python
cPickle pickle
C pickle 1000
cPickle
pickle
12.2
#!/usr/bin/python
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
101
Python
$ python pickling.py
['apple', 'mango', 'carrot']
import..as
cPickle pickle
p
file
dump
pickle load
102
Python
13
Python
try..except
Ctrl-d
>>> s = raw_input('Enter something --> ')
Enter something --> Traceback (most recent call last):
103
Python
try..except try-
except-
13.1
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
code/try_except.py
$ python try_except.py
Enter something -->
104
Python
$ python try_except.py
Enter something --> Python is exceptional!
Done
try except /
except
/
try except
Python
raise /
Error Exception
13.2
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
105
Python
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was
expecting at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
106
Python
/
ShortInputException length
atleast
except /
except
length atleast
try..finally
finally try
except finally
finally
13.3 finally
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
107
Python
f.close()
print 'Cleaning up...closed the file'
code/finally.py
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt
time.sleep
2 Python
Ctrl-c /
KeyboardInterrupt
finally
try..except try..finally
Python
108
Python
14 Python
Python Python
Python
Python
Python
sys
sys sys.argv
14.1 sys.argv
#!/usr/bin/python
# Filename: cat.py
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma
109
Python
f.close()
# Script starts from here
if len(sys.argv) < 2:
print 'No action specified.'
sys.exit()
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help
else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
code/cat.py
$ python cat.py
No action specified.
Python
Options include:
--version : Prints the version number
--help
Linux/Unix cat
Python sys.argv
sys.argv[0] Python 0
--version --help
sys.exit
help(sys.exit)
cat concatenate
/
111
Python
sys
sys.version Python sys.version_info
Python
[swaroop@localhost code]$ python
>>> import sys
>>> sys.version
'2.3.4 (#1, Oct 26 2004, 16:42:40) \n[GCC 3.4.2 20041017 (Red
Hat 3.4.2-6.fc3)]'
>>> sys.version_info
(2, 3, 4, 'final', 0)
sys sys.stdin
sys.stdout sys.stderr
os
os
os.name Windows'nt'
Linux/Unix 'posix'
os.getcwd() Python
os.getenv() os.putenv()
os.listdir()
os.remove()
os.system() shell
os.linesep Windows
'\r\n'Linux '\n' Mac '\r'
os.path.split()
112
Python
>>>
os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile() os.path.isdir()
os.path.existe()
Python
help(sys)
Python sys os
Python
Python Python
113
Python
15 Python
Python
Python Python
__init____del__
x[key]
__getitem__()Python list
Python
15.1
__init__(self,...)
__del__(self)
__str__(self)
print str()
__lt__(self,other)
<
+>
__getitem__(self,key) x[key]
__len__(self)
len()
114
Python
100
Python
if Python
...
Python
2 2
15.1
#!/usr/bin/python
# Filename: list_comprehension.py
115
Python
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo
code/list_comprehension.py
$ python list_comprehension.py
[6, 8]
if i > 22*i
***
>>> def powersum(power, *args):
...
power.'''
...
total = 0
...
for i in args:
...
...
...
>>> powersum(2, 3, 4)
25
116
Python
lambda
lambda
15.2 lambda
#!/usr/bin/python
# Filename: lambda.py
def make_repeater(n):
return lambda s: s*n
twice = make_repeater(2)
print twice('word')
print twice(5)
code/lambda.py
$ python lambda.py
wordword
10
make_repeater
lambda lambda
117
Python
print lambda
execeval
exec Python
Python exec
>>> eval('2*3')
6
assert
assert
assert assert
AssertionError
>>> mylist = ['item']
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> assert len(mylist) >= 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
repr
118
Python
repr
eval(repr(object)) == object
>>> i = []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"
repr
__repr__ repr
Python
Python
Python
119
Python
16
Python Python
Python
cPickle
Python
Python
PyQt QtPythonQtKDEQt
Qt DesignerQt
120
Python
LinuxWindows
PyQtLinux/UnixGPL
PyQtPython
GUIQt
PyGTK GTK+PythonGTK+GNOME
GTK+
GUIGlade
GTK+LinuxWindows
GTK+
wxPython wxWidgetsPythonwxPython
LinuxWindowsMac
wxPythonIDEGUISPESanti's
Python EditorwxGladeGUIwxPython
TkInter GUIIDLE
TkInterPythonWare.orgTkInter
TkInterLinux/UnixWindows
TkInterPython
Python.orgGUIwiki
GUI
Python GUI
GUI
Linux Windows
Linux KDE GNOME
GUI
wxPython
byte-of-python
121
Python
Python
Python
PythonPython
Python.orgPythonPython
Python
comp.lang.pythonPython
Google
Python
PythonPython
PythonDavid MertzPython
PythonPython
PythonXML
JythonJavaPythonPython
JavaJython
JavaJython
IronPythonC#Python.NETMono
DotGNUPython.NET
IronPythonalpha
Jim HuguninIronPython
IronPython
LythonPythonLispLisp
PythonPython
PythonDaily Python-URL!
PythonVaults of Parnassus
ONLamp.com Python DevCenterdirtSimple.orgPython Notes
Python Python
122
Python
A /FLOSS
FLOSS FLOSS
FLOSS Python
FLOSS
FLOSS LinuxWindows FLOSS
Linux
Linux
Linux FLOSSLinus
TorvaldsWindows
2.6
Linux
Knoppix CDLinux
CD
LinuxLinuxFLOSS
PythonC
CD
Knoppix
123
Python
Thunderbird
Mozilla FirefoxMozilla Thunderbird
Apache
60Apache
IISApache
MySQL
MySQL
MPlayer DivXMP3OggVCDDVD
MPlayer
Movix LinuxKnoppixCD
MovixCDCD
CDMovix
Movix
FLOSS
Perl PHP Drupal PostgreSQL
TORCS KDevelop IDEAnjuta IDEXineVIM
Quanta+XMMS GIMP
FLOSS
SourceForge
FreshMeat
KDE
GNOME
124
Python
FLOSS
OSNews
LinuxToday
NewsForge
SwaroopCH's blog
FLOSS
125
Python
Red Hat 9.0 Linux
Fedora Core 3 Linux
KWord
DocBook XMLKate
OpenOfficePDFHTML
XEmacsDocBook XML
Quanta+
XSL Fedora Core 3 Linux
CSS HTML
Python
Swaroop C. H. Yahoo!
LinuxDotGNUQt MySQL FLOSS
Python C#
Robert Ludlum
www.swaroopch.info
CDMA Python
126
Python
Numeric
FLOSS FreeBSD PyGTK
F1
Python Swaroop
PythonPython
Swaroop C. H. Python
Python
Python Python
Python
Swaroop
PythonPython
SwaroopPython
PythonPython
Python
A Byte of PythonSwaroop
Python Python
Python
--
orion_val@163.com
127
Python
2005 1 13 4 02
1.20
2005 1 13
FC3 Quanta+
DocBook
1.15
2004 3 28
1.12
2004 3 16
1.10
2004 3 9
1.00
2004 3 8
0.99
2004 2 22
0.98
2004 2 16
2004 2 13
DocBook XML
0.93
2004 1 25
IDLE Windows
0.92
2004 1 5
0.91
2003 12 30
0.90
2003 12 18
2 OpenOffice
128
Python
0.60
2003 11 21
0.20
2003 11 20
0.15
2003 11 20
DocBook XML
0.10
2003 11 14
KWord
argument
attribute
base class
block
character
class
comment
complex number
derived class
dictionary
escape sequence
exception
expression
field
float
function
identifier
indentation
indexing
instance
integer
list
129
Python
list comprehension
literal constant
logical line
long integer
method
module
namespace
object
operand
operator
parameter
pickle
physical line
sequence
shebang line
slicing
statement
string
subclass
superclass
tuple
type
variable
130