You are on page 1of 98

2008

Byte of Python

 

Swaroop C H

:
Kspersky0

www.linuxac.org
  

 Byte Of Python
 Swaroop C H :

www.byteofpython.info

 Version 1.20
  Copyright 2003-2005 Swaroop C H


  
  ! -"  - &  - -!
)!( -  -.
 - 23
56 4
** 

9 8 (  <; <> << ( ! A@ 9 !3 5 : C FGH ..> 5
<! LH<! )  N<@ 6M  PP ! QH . R
5   <Q (6 ;@G N" T<>  UQL;  43 P @G9 2Q W C9N6

'  ) Z (8 Y6 <; .3 H
**   
"  98!9 >< (!<Q C9 3 H 8 .( 5G )) ! . LH( 4 <! 3 H
]H "; 5 ; @!  U @ U6Q ;<@  C^5 !  H  _4 4!<4
`  !; 9 <Q 8 "   ; H. @ HG 3 H!; b <Q
9 8 " 
H. 2 c G6 3 H9 HG 9 !5 Ud.A 9 9 8 >  3 H! <b4;
  c b @< N 8" T6d.A .
@< N W; ( 9 eG9 UH 8 @!
 ) 2 ` > YH 3 H! <b4; !!
** !!
(6 9  P 9 8 @   c39 N H cH8 R " (3 ) cQg CQd5) cH8
 @<( .A 9 9 8 9 .Qt H 4<W

!@h9 c  (6 iMH H8@ N c  N<@ 6`9 ; !  ; 5 !C3H
! 5 < @ 56 9 cMH 8 ( >  3 H! HHM.U
";  c4 PyQt 4<W  !9 
;" Perl-Qt 9 8 ( <> ] (9
Q9 9  @ iMH  9 > (6 8 .(     !!5
  kQ9 2 O'Reilly
 5 c  9 m>< !8  UH  N  H
  5 .
(9 c53 N  nL(  9 8 ; `] c  >
 @6 (g 

 (  i 5Q C Q  H. 3 H9 HG9 @ W 5 8  <!   5W
LH!< !Ld

) Q9 5  ( 9 8


!  .o cH89 c Q Red Hat 9 Linux
 c  2Q   56 c  36 g. ( 6  9 @ 9 8

 9  C<9 9`M4) 5 Q cMHd  F M4< Q9  cMH L6 C!@ (6
N<@ H C
Q9Q @ 9  < (6 YH  U4 Q 9 > <Q (6 8  C  "
 G! (  !3! M!` ! 4
"  9 !md ]` @ 9 8 (   c (6 U6 m p4
- c W( U6 c"9
 8  - 53 @ A H
8.q .
d.   !3! M!` ! 4 c<  8
A H A CQ6
. ! )@( 8 @< GM N"  G!M
**  
"  
  i C!Q  8 `4 > !)9  GM ; h6 
 Rb
8 ) QG 9 <Q 8  5G9" .
;<b6H.(  ^ (6"  YM W 54 W
8 `4  wxpython Twisted,:C8 <HG eg. 5Boa Constructor N !9
** " ! 
!
)!( "5  http://www.byteofpython.info
d. !
!;
   H C9 d ^ .o C < "; ) !md
(
**(! !#$%
."   !9 -. 2 `.9  W  Q3 UH!
The Creative Commons Attribution- NonCommercial -ShareAlike License
)) ; M (6 &G @  !F ;  2G .( Cb4 ( A U!; )]
 WP 3 9 ( .
; M (6Q CH @< N"  C!Q g   d@ Z 9 C MZ>  C!Q
!Q  cM p4 `.! (6" 
  - C `.^9 
Cb6 Creative Commons <P
`.
 56  5G N ]G U 
!9 ;Mb e .`.
**!
 c"9 8 CQ3 53"  4 
N<@ !M   .  kQ9!
G W MM W M9 FGH9  GM N iM9 (><9! @! Cd
!) .H!;    v
( @ F<swaroop@byteofpython.info>. n
*$+ !$,- ./ 01
 F H `! H R gG9 5<Q  i Z 9 5 @ d9  .P
546 A iM9 Q 59 Yb U` ( C. A. R. Hoare ) ..
3 (6M A U6 5" ! 9 H  56 5^ !98 ) ( C. W. Wendte

02,4



 !L! M:
  Introduction................................................................................................................
!^ 9 8Features of Python ............................................................................................
<]Summary ..................................................................................................................-
! 9 p Why not Perl? ...............................................................................................
  ! 3 HWhat Programmers Say ..............................................................................



* 9 8 (  <; <> << ( ! A@ gG9 5
 @< )  N ) . G
4| (6 ( ) <5^ C (6!< !9  2))  > 5<@ C!Q 3 9

 ! 67 $  :
9 8 (  >  <5) 3 H
<Q . M 49 @ ! G N<@ gG9 CH
 C!Q Q6 5 3 H. L


@ 9 8    56 9 H NG4 QHF 29 CQ3 8 > 3 H 8
9G )@  g (6 nHgQ !A3 @< mQ N!` .
)
} mQ" T!G ^!9  (6 C`4 G(.
::9
W" Guido van Rossum 6 )  > 9 8 5<@ n<F; Q9 )A|5 Z@ U
@ Hg )" )9 ( < 9Q8Lg"" "Monty Python's Flying Circus
 C8 59Q8
(  C M >" @<F @ 5 4` nG 4A9   5). 5M
 =$ < 6:
**:?$1
9 8 > Q9P gG9M .
 9 R H 8  
UH <> <^ @< N W5
^<3  !
QHF" )A!QG H 8  @ m)
 .5 U ; Y^ @< C N!< 8
<> . 5G4
** * - :@-A
! )9 8 )>< <5 H <Q (6 599 .3 H 8  M  <5) 2@ ! ) nH. T
**! , 2:
9 8 ( 8 !` (Free/Libr and Open Source Soft-ware) FLOSS Y<gH RM ! 4
!`.
HQ9 gG9!; M9  &G" T3 H
 4 !`  kQH9> @<5
)] ^ 3 9 (6 5   Q c U!;  CQ4" TP.
 54 `H N<@ FLOSS Y<g ! !3"  (6!.6Q
"  )H 9 8   P -  
U d. !G C9 5GM ! !3" 
e6  9 8 .Cb6

:1  A$+ /!** <


5 ]G " ( C8  G!
 C49 nb N 9 M A 89 (6 R H 2  @
.& ;3 9
:  **
. !`Q( N<@ C!Q 5<Q!  )  M > 89 CQ    !`4! R H QHg m
N<@ ; >2<g !` T" N<@ C!Q  5! 89 ><9 R 9 UQ`  C
.m< . @!23 4 U6 !9 
c .dF
.
: 2D E F-G 6 I JD 
Linux, Windows, FreeBSD, Macintosh, Solaris,
OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX,
VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus,
windows ce pocketpc! (4  H! N
: !1, < **
| 2<g**;
>< NC++ C .>< ` 5< M  C++ C C8 ! /Q!3 > (6  R 9
)] ! ]< ]9 (binary code i.e. 0s and 1s) "  L "5 5!<(
(6 H " N 2<`  R H& G9 linker/loader  R H @ ><; .<!Q
. U<>
 H R H C> e6 .(L8  N! 3/! N M A .  89
<P <> N   " bytecodes N!G e) C N !` 4 M 89 h6 <. .!`
n<9 Q @<; p U i 89  )]89 C5)P CQ3
(  6 "C .U<>  53
] 89 R 9 CQ3 b & " & 5<!M e9 H M  R H! 3 
! C!Q Q9 .  H! 5 N<@ ;9 ]89 R 9 &G 3 ;! iM9  !M 8; 9
Object Oriented K $D** <
object-/5 ! L 3 H "; procedure-oriented/5 ! L 3 H @ 89
 M! R H h6 procedure-oriented/5 ! L 3 H( <> ( @ 46 .oriented
h6 L 3 H( > 6 .5 ! @ )]R H Qg
) cG ( 

  89 > .L  H 9 !6 !3 ( objects/L  M! R H
C8 H<> 9 5] @ 9 {Object-Oriented Programming} oop C!Q gGH g9
. 6 C++
Extensible  : -**
A  . g kQ9 ;    Q )C!Q   Qg
N(  ) 6 c
. ;9 ]89 R 9 U ]G Q9 C++ C ><9 ;3 9 ^3 " 9 !;  4 
Embeddable $ M- -**
. ;3 9 ( ]G! 'scripting' 
 g@ C/C++ R 9 !Z 89 !b ;!
Extensive Libraries A1 /-N  7 **

regular :56 !9 Q P ]< C!@ N<@ )@ ".


(  6 !]Z H ) 89 H
expressions, documentation generation, unit testing, threading, databases, web browsers,
CGI, ftp, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical
. 89 cH8! ! L "  C  ".m N<@ !Q ( P W user interfaces), Tk
.'Batteries Included' (6Z M g9). 89 4G<6 (6 N!G" 
:C8 3 @ .P ! @ H! Q )   H!< HG9 ;2 N
. 8 8 Python Imaging Library, Twisted, wxPython
:%
R 9 9 CQ3 ( !^ P G R ^9 !3 M( 6 5 .  
8 > 89
.Q!  5G C 9 !3 89
!$ Q$ 
. <>HQ  !` 4 G4 3 9 > .P ( HQ 9 dQ6 Q A c
! ! ;G49 G @ " cH
 c! 9 9 (6 H R 9 9 c ; nH)
5 9G `> R H( 6 H < @   >5) U3 9 9 h6 . HQ9
.C!Q 3
93
 M  H R 9 9( 6 H 3!9  R H T" YH`    )@N<@
! ( 6 9 ><9 H R 9 9
8( 9 9( 6 C5)  Z 8 C5) 9 ( 89 N<@ R H h6 9 !9
. <`54< <9

9! L6 3 9 cH ( <! @  P  ))( C9 5 )]9 


9 ><9 23Q 
.( HG9  QHF cMH 5 i 89 (6 4
.5( M  5  )W N<@ 5 Q 5 > H Q 9 > cQb.
. "59 n<Q GM  h c 
5 H A <H! 9 ^ M!
the Comprehensive Perl ) CPAN ]! b H! ( 9 (6 59 Q   ( 5!^  
modules/ R ! ^ )A{! ( H N<@ H C  P( }Archive Network
) M U9  ( !; 9 <!@ U9 !; -- n!Q 3M< m CQ< C "FGH9  9
5  C!@ U 89 @ ! 8 9 H CQ3 ( H)P  . modules/  T")] 9
. comp.lang.python
(6 89 N 9 ^< ! C C!@ <(
Q . 89 89 F c

89 C8  ! 5!!` Q! 9 > C C>9 ( `!!  Parrot virtual machine ";
. Tcl PHP Ruby C8 .P G4!"; <>
CHG!( 6 89 C. 9 )] ! N<@ ! 
9 ; " ; HG9 ; UQ 
e6 <@  N<@ .  89 > A9 CPAN Q( 6 H
C( 6 Cb6P; ; M!) "
.M)   m
/!7 * 

.6 G { Eric S. Raymond} ESR 8  5! m@ U    5!! 9
b{ H L' }The Cathedral and the Bazaar'  :Eric S. Raymond

. 4! !` Y<g` Z " -]


3 H ( > 89 cMH  Python has become his favorite programming language/ " :

. 89 (6 ( g. N( 6 ( (M 5<! ! ( T" HQ<  " b4!
"c++><9 4' "Thinking in Java' '6<> 9 4 '5 2  :Bruce Eckel
( 89 !  9 U :  . 89  8 U<Q  >
 p : '  Thinking in C++'
complete interview < < 9!
 .R H!< HG9 C5) P CQ N<@ ^<>   ( 

.C4!^
Guido van ) C( 6 iMH  Lisp >  U9  Q : Peter Norvig
( ; N U Rossum

d.
(  6 Y " `nM !; Google ^3 A ! ^L c 89 :
()5 CH
56Q < g! Q!! L
(6 89 > cQZ ( . Google Jobs M4 (6 m
.3 H
userlinux. opensource.org  G)!  : Bruce Perens
G6! 89 Z 
. Q QL9  @ p )
Q  C!Q Userlinux
.Userlinux CH
 @  ( ) GL 3 H > YH` (9 9 c<Q6 !<8

6 02,
6 .$2D
 M!
d] - ] ( G! - -Linux/BSD ( ]G!
FreeBSD C8 BSD m {
 . Z}  ; 6 C8 p Q  C
!QG c
. ; m N<@ H8 89   H!
console C8 )  R 9 Y6 p Q  N<@ @CQ49 89   H.A
 P " C.( Gnome terminal
$ python -V
Python 2.3.4
.; m @ N<@  ; @!HG9 <] ; shell (6 !/iM!  d@ ( $
e6 ^ " 59 iM! N "; )  $
. 89 cH8 @<; Uh6 A Td@  P( 6 Q  C8 ]G<  @  Q! kQ9 c
:T" C8 ) N<@ c<`  N<@
$ python -V
bash: python: command not found
.C
!M U  QHG! "  @H8 p 89 TQ   M( <; 6
;
m N<@ 89 2` F
 @ M T"( 6.
p (6 yum C8 m( 3 (^ M R
9 )]9 binary packages 2 
m( 6 pkg-add - p
 H( 6 apt-get - p
 (6 urpmi - 6
.& FreeBSD
.g T"! Q)A c
9 A
`
M) :9:
.5H89 
 5 N 5]G ; Q9 .o binaries ^C
!M !; ; @ d
9
 9 c H ) ! .UH8 source code < !`CH C!Q9 89 2! 
. 2
: D 9  I1
( 2.3.4 : ]G

 " !
)8H ]G .o C! Python.org/download
^9 

 >8! 9  F >b (  6 c9> 9.4 e6 5!3 <H ( . <!T" 9 N
.|  9 N<@ H R 9
C8 2 ..P 3 H
:K$7D
 `. ; 4
 ! T"   Any ] A 6Z  
cH8 Q9 . (gQ  @
. IDLE
(  gQ A T" Hg9 .!<( QG 89 R
9 C!M9 !
% 70 ( 
 8! M
. (Z6 C9 5!m N<@ H8 89  @ 
) H p (<!QG C
i < 
D ?! ! + 6  A
C9 PATH C Z 
M ;h6   g) 89 !Q) N<@


.YM
49 e>Z XP 2003 2000   HG9
.Control Panel -> System -> Advanced -> Environment Variables
" :6Zh9 
EDIT .'  System Variables' G
(6 PATH N!G! !>  N<@ e>Z
2)! C ) C!Q) Hg9 . CQ49  ! gG 5( 6 ("" 
9) " C:\Python23
.;
C: \ Autoexec 
<! N(
 gG b "6  m
 P&
G<
. m C> @
""(  9) 'PATH=%PATH%;C:\Python23'
.AUTOEXEC.NT < C
!QG NT   HG9
:I
R
9 )]9 UH !; ;  @ .;
m N<@ 89 c
H`  ; C!M! p m HG9
.;Q(  3 (^ M

q .U<@  9 R H < C!M d. ;"  5G9 89 cH8   m HG9
.;
m N<@ 89 c
H`; 9
4) `@ 6
. 89 N<@ P 3 9 2
) C`4

\ 6 02,
F 4? I
: 
! < `Q) -  ` M . - interpreter prompt G4!  /iM !Q) -  !
d] - @G N<@ ` M - Executable "4< <9 89 R 9 - C
!Q  - output ]:
*
C> _4M 2 
<!; " Q) . 89 (6 'Hello World' <R H C>
 q)
. 89 R
9
-:;
3 9 C> 89 )]
F  
( G R 9 d. ) interactive interpreter prompt (<@4 G4! iM **)]
. g < C
!QG
 q ) .** )] < `
the interpreter prompt !1,  ](! A
. {console / terminal } 6 `( 6 python !< 99  P g) N<@ interpreter 9
.Hello World : @ H@ R  2
3 .Enter
4!9 @ H 'Hello World ' :2 q
 >! C c
QZ{ Dos}  P g) interpreter G4! C> !; : D  I1
.IDLE R
9 C
!QG !; ; @ d
9 .Ld C9 PATH
.Integrated Development Environment   < >g |9 @ H@ IDLE
Click on Start -> Programs -> Python 2.3 -> IDLE (Python GUI)
.b IDLE !< QG 5! p
 <!QG .
:9:
. .prompt for entering Python statements 8H G4! R H iM .   >>> dQ T"
Example 3.1. Using the python interpreter prompt
89 G4 ! Q) .3.1 8
$ 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.
>>> print 'hello world'
hello world
>>>

printC
!QG M .single Python statement e6 c<.
 c ! 6 gG R
; gQ 89
_ A
.U 5g@ value !
 Hg (4 W C9)
. N<@ 6 Hg T"" Hello World" v  U g@
 M 
: 6!  I  $,$
6  ]G IDLE C
!QG c Ctrl+ d (4 N<@ e>Z prompt R H<] 
.ENTER 4!9 @ H Ctrl+z (4 e>Z 9  P g)  (  6, .BSD/LINUX

2D  ! $%


 M  .
. !`
4<! 9 M
M  !`
4<!( 6 89 R
9 9 C C
H

9( 6 @ G) 3 M! .5 ( G ; ] M! ] 2
3 .M( 6 5 
89  )g9 (;
6
) ;
W N C
` @G  8 M <; C
Q3  5G9 89 R 9
. 8
^P C
 iM9 ( 2 <9 ) syntax highlighting ())  P
H<g!
.U<!@ 4; `
3 9 ; NG N 89 (6 colorized  < R
H< 4<]!
8 syntax highlighting C!Q9  IDLE i .IDLE !Q) @<;

C
!QG c
..!  Z IDLE !Z ;
3 9 C>9 ; !G C8  89
; P syntax highlighting C!Q9  A UP ) . U - Notepad C!QG A :. md
.A (  ! )6  5  ( H 6G! m )indentation <  8  @ A U
.; C
!Q o @G) (VIM b )IDLE C8 3 M!
H. 3 H c . M! 9  ]8<; 6 tg]d Linux / FreeBSD C
!QG c
 4G)
P M!!  59  < A .Emacs VIM C!QG ;! ! 6
. 89 N<@ ;3 9 9 !5!Q)
( KATE C
!QG |" !; LH 3 H c .(3 9 2<WP VIM C
!Q) ]`
<Q  9 ;( h6 Emacs VIM <Q c
 b
(6 HW c(   6 .<b4!(
.QH( ! 6 ;  4 ;
) i !5 ! Q)
.. 89 M! < ! L m M!< .P  ^   ) ] c
. 8H (<   g |9) (IDE (Integrated Development Environment b!; ]
h6 89 (6 H R
9 99 H  @ .C4 <!^ 89  @ ( IDE !  < L
.M( 6   4
 ! IDEs R 9
. 5)   8 89 R 9 9 C
Q3 56 -  M .  .  
2 ` - I
U<> UH R 9  3 9 > <Q ;<H) (6 c <! U  < .3 H N Q @ q
Simon !
.U<> @ 'Hello World' :  U<Q6 ;<@  C -- 'Hello World' R 9
. 'Cb6 C9 ><< Q N<@ ;@G! 3 H 9P  ^ <Q 98!9 5 " :Cozens
helloworld.py :)9 Um4 ( R H C. M! .( 6 9
)] !< !`3.2 :8
Example 3.2. Using a Source File
#!/usr/bin/python
# Filename : helloworld.py
print 'Hello World'

@ () !  ! !< !` " ( Source file: code/helloworld.py)
(U ;<!M
:  P 9( Linux terminal or DOS prompt) C/6` Y6 nF @ R H " C>
$ Python Hello World
R .Ctrl+F5 Y4!`   . menu Edit -> Run Script )]IDLE ]G c
.T H ! output
"Beginning Perl" +, $ ) perl6/parrot   $% $'[ 1]

Output
$ python helloworld.py
Hello World
( 6. 89 (6 ; R 9 C> (6 cM3  -- !5 ; Td@ H ! R N<@ c<`
!<@ ..  R H C> Td@ H ! eHb9 !" R H 9 N  g. N<@ c<`
case-sensitive P M )GM9 ^! 89
..P( 6 P H M NP( <! 6 p >` M_ A -- Print G A print !< :8
 ) ! " -- g) C( 6 P M CH
F  d@  W6  @ b
.nA c
( 6 5
:0 A `$*
(  --" comments - <Q ": <!T" N!G .R H g) ( 6 m@ 
. R H  " 4  ) P( 6 n<Q # ^  ! N<@
@   shebang line N!G ( . P gG .  8)9 <Q] G A 89
R H " p\ p H] " h6 R H) 9 @ H # # @ H@  !< !`6
.R H" 4 @ interpreter G4! " C!Q 23
platform ` N<@ R H C> !L ; h9 U @<! .( G( 6 C`49 )  "
. python helloworld.py : P C8  P g) N<@ H interpreter G4! M d.
@*
 4  " -- R H( 6 !5! C4 kQ9 ; 3 9 (6 (d@  < Q)]
) Q9 ;G4 c !  -] "  ".R H U9    56  5G9 ! iM9 ;3 9
!!5
( print !< .'Hello World' :-@ " Hg9 e6  -- Python statement (< (< Q
!! n< A --string `< G<) H@9 5'  Hello World' C Q operator
@ H@ CQ49
.Q9 !6 C`49 M<g`! T"( 6 iMH)
Executable Python programs $,D- -
6 b!
gG @ b4 kQ9 5]  G 
  p / p ( ]G N<@ A nHg A "
 P)] 9 executable permission "49 Y `R H g@ @< Q A .R H A
. !`R H C>  Chmod
$ chmod a+x helloworld.py
$ ./helloworld.py
Hello World

Q9.m] ( G !3 A g@9 "4< d9


U<Q3 <! Y]  >  `G chmod 
(6  R H " N  / .]G  .
!< !`M nF @ H R H" 4 h6
.(M C
Helloworld / . : M N<@ U<> helloworld N! !< G @e6 ;! Q 8 P CQ3
<!( 6 A gG( 6 M! G4!)] 9 R H C> U<@  Q m P C!Q Cm)
.!`
N<@  c    -- R H G eHb9 Q c  R H C> N<@
q c
G (6  UA(  6 R H ]^ d. ; CQ4  !; R H C>

(6   P C( 6 R H @ " iMH m h6 R 9 C>9 c!


!< .PATH |H >
FG9 C9  C( 6  R H " CQ3 ! .R H " C>  PATH |H > G
.PATH G!( 6  UA  N& " !< !` G
$ echo $PATH
/opt/mono/bin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin
$ cp helloworld.py /home/swaroop/bin/helloworld
$ helloworld
Hello World

 P 2 n9G  P 3 P P R H& G9 


TG  "M  R H C> q !; M shell N ) !>  CH
$ ^   echo  P)] 9 PATH G!! @ >
:
! " !> "N M9
$echo $PATH
] "G! ) swaroop i PATH G!( 6 P  /home/swaroop/bin/  M
N<@ ;9 ] ]G!) Asimilar directory C !C )  @ . @m N<@ U ])
9 nF @ ; !  --PATH >!< . d b !; ;" CH .5
PATH=$PATH:/home/swaroop/mydir  P
PATH >! N U6Z "  C /home/swaroop/mydir/ i
U .( 6 c
( 6 R H C>  4 9) 2  c  4 g T"
. p 6F (6 5 ]G (  P TW cd  P C8 5<8 ;G4  n<. UH
. (p4( Q 5Q! nHg cH )R 9 U!G ! W.r.t. Python :K$7D
@G! N<@ ` M
4 !; )] 89 (6 statement 9 ) @  C9 < Q N M9 c
N<Q6 .interpreter promptG4!`  @ )]  .  4 ". R H( 6 3 !@ G!
- C] ]^ G (str class Hg@ @ G Q  P " -- help(str) C> 8! CH)
| 3 H9 n<Q! C`4( 6 C`49 5) Classes Hg .;3 9 (6 U ]G (C!3)
object-oriented programming 5!
:9:
@G! <] q e>Z
 !^  6Q! help () )]. 89 (6 H<  @ ( Q N<@ ` M !; C8!9
!5G4@ G! F )]
> M N M9 c6 print C8 operator C Q @ @G N<@ ` M N M9 c(  6
/ p N<@  5G9 ; !  .2) C9PYTHONDOCS environment variable |H
.ENV: P)] 9 p
$ 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')

@G bM) (  54 8H ! N 'print' M " H


A  d@ c ])_ ( d)
.@ (HF U A (' print' 
 Q < HF 4<]
  -- 3 6 (6 ]G! R H< P !
c ])@<! (
.]G
:d]
q @ 89 ]G c q . 5) C9 89 R 9 C> _4 9 N<@
q  23
. 89 @ 8 4 <Q

" !02,
$  4
  
Literal Constants ..............................................................................................6M c9 8
Numbers .....................................................................................................................@P
strings ..............................................................................................................` C)dG
variables ...................................................................................................................!>
Identifier Naming ...............................................................................................Q!! G
Data Types ..........................................................................................................H
Objects .......................................................................................................................L
Output ..........................................................................................................................]
How It Works..........................................................................................................C!Q
physical lines Logical .........................................................................g! ! gG
Indentation ...................................................................................................................<8
Summary ...................................................................................................................d.
kQ9 ".  -- ; 8 CQ4  C "; ! p (4 A e6 'Hello World' @HF
!>c9 8)] 9 89 (6 "nM ! .5 (N<@ ` M 59 2@d d.!
.constants and variables
Literal Constants $+! c6
'This is string C8 <! e - 39.25 231 5 Q : ( 6M c98 8
:(8  P . 6M 5!
]G c 6 5P literal 6M N!G T" ."! It's a string"
5< T"56 ;" .> ! A 5!
P constant c9 ( -- .o (A 5(  6 5G4 C8! 5
.lliteral constants 6M c9 8 59 5
: G4
<4 @ long integers < F MM @integers MM @-:
 Q9 89 (6 @P
.complex numbers H @ floating point !LQ
.e6 YM ( ( @2 :MM`@ P N<@ <8
.H 5 MM @e6 ( < g MM`@ P
(6 10 N   E-4.,52.3 E-4, 3.23 (`. float )floating point/!LQ< 4< @ 8
52.3*10-4 (Q52.3*E-4 M T"
-4

(2.3 - 4.6j) ( -5+4j) H@ !P< 8

strings $2D 0 :1
. ! @ <!3 3 )) ( .M< G<) ( : strings
;<@ ;" 5H ( 89 R 9 H 2 C( 6 strings )]9 ! ; ) Z g) H
: 89 (6 ` C!3] G  ; .(^ 3 N THA
() 4! H
A  d@ ** )]
C8 bH G!' ! Quote me on this' C8 H
 d@ )]9 string - M ;!
. (_ ! 4M tabs  W4
: double quotes ( ")  !^H
A  d@ ** )]
( C!3( 6 ! !  g p49 C!Q " " double quotes  !^H
A  d@ !Z C!3
"What's your name?" ; N<@ 8 . single quotes 4! H
A  d@ !Z
triple quotes d8 H
A  d@ **)]
 d@ !; )].d8 H
A  d@ )]9 ` C)dG g)P Q C! M ;!
.d8 H
A  d@ !Z M9  !^4! H
A
:8! CH) N<@

'''This is a multi-line string. This is the first line.


This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond." '''

Escape Sequence
CH) N<@ !< 3 T" M  ; ( ' ) 6 H
 d@ N<@  M <!3 ;   6
H
 dQ9 (What's your name )HQ T" M ;! A the string is What's your name 8!
H
A  d@ CQ3  @<; Q) ".(5 !< 3 H i ;H ) 89 P 4
; 3 " ! .(NP H
A  d@ @ c5!< 3 89 Q d|) - 5  A  
\ { "- 5 CH
} 4! H
A  d@ CQ .(5 C)d)) escape sequence N!G@  G!9
.\ backslash. 4<]< L! F N UH'-'What\'s your name?'. :*   ( $%&      "! 

 ( $%& 7%" What's your name?" % % 2 3 3 01 %  .



$%&A ! 7% 8 > escape sequence 7% = 8 . ;$%& 8

K K  1 . ;$%&  
 "! J   G*  D B;
escape sequence \\. 7%
 K backslash B ( 7  L
  - * !$%& 7%   8%  B   3   
  K% - \ n %  3 escape sequence. 7%  0! > $
This is the first line\nThis is the second line 1  .
escape 5 C)d) Q  . - \t tab escape sequences  . L6 .
.  UQ4 8 N e6 ( sequences
N!<  3 5( 6 backslash \ 4<]< L! F <!3( 6 Umd(  @<
8! CH) N<@ . g) 6Z 9  CH! gG( 6 !G `< G<G

Variables !$<
F N M9 M -- d
!  Q )YH` ! e6 literal constants 6M c9 8 )]
eHb9 !>.( ` 6  !>5m i ".b 5 ( 6 2@d<  Q!  ]^
cG !>.Variable > )]9  !; ]^ (5!
4 ! UP - 5!) N<@
literal 6M c9 8 pQ9 .< Q! kQ9 ]^i ;9   ]H!  3M ) ^
. )!5Lg@( 9 !>T" N  <  F N M9 c constants
Identifier Naming Q!! G
;<@ @  kQ9 .  (Q NgQ  ( )!6Q! . 6Q! N<@ <8 !> (
: 6Q!! G 5@H
(upper or lowercase)  >H 39A M  9 A Q! P M**
.('_') underscores b4] F
F (upper or lowercase)  `>H M !  Q! ) 9 **
.(9-0)
.('_') underscores b4]
cG myname Myname 8! CH) N<@ .case-sensitive P M )G Q!** )!
..A T" > .P( 6 m >` M NP( <! 6 M H M_ d . 9
i, __my_name, name_23 and a1b2_c3 :M 6Q )!P <8
(& ...... 39  U i8 underscore  H( 8( L3  P Q!_ d)
2things, this is spaced out and my-name : M W 6Q )!P <8
dash - F N<@  M i8 - W6 6G N<@  M( 8
 9 H P Q! _ d)
(underscore p
Data Types ...$7 
:()) P P .Data Types N!G H 4<] P 
C! 5! Variables !>
P  4`   ) 4( 6 . CH
 ( 
strings ` C)d) - @P
classes /Hg)] 9 9 ]
Objects . D
. Q TQ!9 " !` object L U N<@ R H( 6 ]G (N  89 "
( object L ) U@ (  something - " (U@  AH6
Object Oriented Programming users :* $D  /!7  I1 9:**
@P ) object

@ H@ (C NQ!9 5 ! L 3 H 3 (6 


3 9 > 89
. functions N`

Variables literal constants 6M c9 8] !> G  q) Save the following
. R H C>( <   6 ( 8!_ 4
How to write Python programs :6 + b!7 .` $
: ( M N<@ 89 R 9 C>_ 4M  
)  `@6 q

.; Cb4! ` M Y6 .


.( 8!( 6 ; NgQ! R H C. .
!  9 U<@ 4  H n<Q( 6 !" R H( 6 H!) A9 <!_ 4 .
. Py.  9 U 4M! R H
IDLE )]python program.py (  P9 R H) 9 @ H 89 G4 C> .
c
( 6 YZ ! executable "4 4<! F  )]b !; .R H C>
.n9)
Example 4.1. Using Variables and Literal constants
# 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

Output
$ python var.py
5
6
This is a multi-line string.
This is the second line.
How It Works b!7 0 G $,$
P !> N U!
(i) literal constant (6 c9) h9 !
A .R H " C!Q; 
U9 >( H |  Q H 5P statement Y `N!G gG " .(=) operator C Q!)] 9
"print Y)] `9 i !
QHF ; Q9 . U! i P ) !> g9 M T"( 6
.  N<@ i >!@
! Hg9 U 8 A (QHF C9 e6 
. U! N<@ C`M!
6 U@HF  .(Q 9 U ]^P( !> 6  !]^U! N 4Z h6
. U@HF  s >!< literal string  )6 C8!9

Note for C/C++ Programmers. ++ \ /!7 9:


Y @ `declaration d@   p .!
N) h9 e6 ]G Variable !>
. ]G! 6Q!
Logical and Physical Lines $
?D ? 1 ?  1 .
 Y `89 (U!54 )T(  g! gG .R H 2  @ T )!(  N<Q4 gG
UQ n9g( g g) U<9 Physical <( Q6 g) C! Z 4 89 .single statement
Logical
(6 U )! U(  6 gG N<@ 9  -- print 'Hello World' :(g! gG N<@ 8
. g) n9g b " (M!
(6  5) 8  CQ3 ! g) C single statement  Y! `Q) N<@ 89 3 !Z
. .
<4)] 9  " M @<;  g) N<@ ( g g) 8 M  c
8! CH) N<@ .statement Y( `g! gG 5 N );(   F !
i=5
print i
: "UH@<  4 p49 
i = 5;
print i;
: (< ! U9 ! C p49
i = 5; print i;
: "N
i = 5; print i
8 )] .  g) C e6 ( g g) 9 N<@ cH8  9 (( 6 ;

F !`< 4 23 ( 4 . C F (g! gG  A( g g) C   g)
U<4 c N  5 ]G   M( 6 .(
  6 c
 ^ N  5P m 
. 8H R 9 (6 UF !
. gG! b N Z 9  " .(<  ! g) @ N( ! g g) 9 N<@ 8
s = 'This is a string. \
This continues the string.'
Print s

:R gQ T"


This is a string. This continues the string.
:C8!9

print \
i
print i

C8 eHb9 (

M " .( \ ) backslash <L! GQ F )] N M A ;!( Z 6 
} Q3 [ square brackets] Q9 ( parentheses) d
9 (g! gG] G@ 
2 @  C!Q !;  " .implicit line joining (!b! bA g) N!G" . { curly
.  ` 4( 6 L)]  9

: Indentation
{!! < 2< "8 N!G 6 5H"5 W4 H 6G! m TQ Y<g` }

N!G"  . 5   gG 9 (6 bH W4 CQ49 . 89 (6 !5 bH W4


Indentation
<8 G M (6 ]G (g!gG 9 (6 (F 6G!)))P bH W4 .
. Statements H! 3 M ]G T9 "(g! gG<indentation level
C .indentation <8 p4 5  23 2 N H G ( statements H( Q"
.A ` 6 (6 blocks !  N<@ <8 ) .block < N!G H! @ 3
: 8! CH) N<@.g. N !  F] indentation <8 T   @<; "
i=5
print 'Value is', i # Error! Notice a single space at the start of the line
print 'I repeat, the value is', i

:g]; " gQ U<> @


File "whitespace.py", line 4
print 'Value is', i # Error! Notice a single space at the start of the line
^
SyntaxError: invalid syntax

2 9 H] i 89 U  g] .(8 gG 9 (6  W6 6G !_ A
; " NQ .YM` U  N<@   W R H C8 .MM W R H( " 6 syntax M
!L 5 ]G ( GL < 8)9) H  block < 9 FH@` 9 9 gG A
n6 (6 M C8 A ` 6 (6 5<`4 ) 3 C )] 56 ;! ( AM .(M QHg9
.. H
@$-6 0 A`
 $How to indent
<] H@ YM` M N<@ C!Q A 5 @ db6 <8< ( tabs and spaces) dQ 3] ^G A
. indentation  G C 6G 9   tab ]G  9 ( .!`

. " T 2)Pd8 < .<8A ; ]  )] !)9 5indentation .


 A)] <)A . 2GM6
:I
q Q9  @< N 8 C4
 ! A ^ N P P C8n6 (6 M
H .control flow statements @< N ; )` ) !  YH  (6 T" .C`4

QI 02,
!$7A 0A
Operators and Expressions

Introduction ............................................................................................................ 
Operators ...............................................................................................................C Q
Operator Precedence .......................................................................................C Q H)
Order of Evaluation............................................................................................ 2<F
Associativity..........................................................................................................g9
Expressions .......................................................................................................HQ
Using Expressions.. ...................................................................................HQ)]
Summary..............................................................................................................d]
:
 **
.expressions HQ N<@  M 599 ( ( ) logical lines) ( statements H 2<W
operators and operands C @ N 5!G ! HQ  .+ HQ P eG9 8!
+ C8   9 5<8! ! (  C!Q9 (  U6d. g! G! 3 )4 ( : Operators
. keywords/4!  <!
@ H@ HQ M T"( 6 .operands/d Q! N!G H kQ9 2<g : Operators
operands
. 5 )]operators :C Q  ]`  39 )  Operators
8! CH) N<@ . H interpreter G4!)] 9 <8 P( 6 gQ! ! G ;! : g$ -
Python interpreter prompt 8H9 ]C@4! G4! )]  3+2 HQ H.A
>>> 2 + 3
5
>>> 3 * 5
15
>>>
Table 5.1. Operators and their usage 5  )]Z C Q H
Operator Name
+
Plus
-

Explanation
Examples
Adds the two objects
3 + 5 gives 8. 'a' + 'b' gives 'ab'.
Either gives a negative
number
or
gives
the -5.2 gives a negative number. 50 - 24
Minus
subtraction of one number gives 26.
from the other
Gives the multiplication of
Multiply the two numbers or returns 2 * 3 gives 6. 'la' * 3 gives 'lalala'.
the string repeated that many

Operator Name
**

Power

Divide

//
%

<<

>>

&
|
^
~

Explanation

Examples
times.
Returns x to the power of y 3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3)
4/3 gives 1 (division of integers
Divide x by y gives an integer). 4.0/3 or 4/3.0 gives
1.3333333333333333

Floor
(
9 9 !G R Q
Division
Returns the remainder of the
Modulo
division
Shifts the bits of the number
to the left by the number of
bits specified. (Each number
Left Shift
is represented in memory by
bits or binary digits i.e. 0 and
1)

Bitwise
AND
Bit-wise
OR
Bit-wise
XOR
Bit-wise
invert

Less
Than

>

Greater
Than

<=

Less
Than

8%3 gives 2. -25.5%2.25 gives 1.5 .


2 << 2 gives 8. - 2 is represented by
10 in bits. Left shifting by 2 bits
gives 1000 which represents the
decimal 8.

11 >> 1 gives 5 - 11 is represented in


Shifts the bits of the number
bits by 1011 which when right
to the right by the number of
shifted by 1 bit gives 101 which is
bits specified.
nothing but decimal 5.

Right
Shift

<

4 // 3.0 gives 1.0

Bitwise AND of the numbers 5 & 3 gives 1.


Bitwise OR of the numbers

5 | 3 gives 7

5 ^ 3 gives 6
The bit-wise inversion of x is
-(x+1)
Returns whether x is less than
y. All comparison operators
return 1 for true and 0 for
false. This is equivalent to the
special variables True and
False respectively. Note the
capitalization
of
these
variables' names.

~5 gives -6.

5 < 3 gives 0 (i.e. False) and 3 < 5


gives 1 (i.e. True). Comparisons can
be chained arbitrarily: 3 < 5 < 7
gives True.

5 < 3 returns True. If both operands


Returns whether x is greater are numbers, they are first converted
than y
to a common type. Otherwise, it
always returns False.
Returns whether x is less than
x = 3; y = 6; x <= y returns True.
or or equal to y

Operator Name
Explanation
Examples
Equal To
Greater
Returns whether x is greater
>=
Than or
x = 4; y = 3; x >= 3 returns True.
than or equal to y
Equal To
x = 2; y = 2; x == y returns True. x =
Compares if the objects are
==
Equal To
'str'; y = 'stR'; x == y returns False. x
equal
= 'str'; y = 'str'; x == y returns True.
Not
Compares if the objects are
!=
x = 2; y = 3; x != y returns True.
Equal To not equal
Boolean If x is True, it returns False.
not
x = True; not y returns False.
NOT
If x is False, it returns True.
x = False; y = True; x and y returns
False since x is False. In this case,
x and y returns False if x is Python will not evaluate y since it
Boolean
and
False,
else
it
returns knows that the value of the
AND
evaluation of y
expression will has to be false (since
x is False). This is called shortcircuit evaluation.
x = True; y = False; x or y returns
Boolean If x is True, it returns True,
or
True. Short-circuit evaluation applies
OR
else it returns evaluation of y
here as well.
Operator Precedence 0A  $
7
! b!< Q9 A! 3!< Q9  C 2 + 3 * 4 C8 9G <!@ @ HQ ;  
b @!< TQ ; A  23 b @!< H]  8( !) 6 Z@< 
.addition operator !3 @!< higher precedence N<@ H) 5 multiplication
8 )N<@P H)P ^ (  C
)NP H)P9 9 89 (6 C Q H)9 9 gQ ( 3
.( ^
N<@P C Q CH
3( 6 NP C Q
! GM9 ) 89 h6 gQ! HQ C.9 U TQ ;
.3! L
(6
;" !C< Q  CH) N<@ ; 5g@ ( 89 (6 C U H ( )3
.U9 ;M`
C Q< H)P M operators and operands d Q!/M C Q! 3 ( )
P)]
8 C9 M 2 + (3 * 4) 8! CH) N<@ .( 
  6 C5); 3 9 CQ3 Z 9
 Z
L>(  H A dQ9 GM9 ]G 23
) ( P .; Q9 (C " . 2 + 3 * 4
.( (4+3)+2 C8 ) .M@

Table 5.2. Operator Precedence


Operator
lambda
or
and
not x
in, not in
is, is not
<, <=, >, >=, !=, ==
|
^
&
<<, >>
+, *, /, %
+x, -x
~x
**
x.attribute
x[index]
x[index:index]
f(arguments ...)
(expressions, ...)
[expressions, ...]
{key:datum, ...}
`expressions, ...`

Description
Lambda Expression
Boolean OR
Boolean AND
Boolean NOT
Membership tests
Identity tests
Comparisons
Bitwise OR
Bitwise XOR
Bitwise AND
Shifts
Addition and subtraction
Multiplication, Division and Remainder
Positive, Negative
Bitwise NOT
Exponentiation
Attribute reference
Subscription
Slicing
Function call
Binding or tuple display
List display
Dictionary display
String conversion

.d` 4( 6 5 ) 5d. ! (  C Q


- + 8! CH) N<@ .Td@ H! 3( 6 !L( 6 ` p4( 6 cQZ H)P( 6 G!  Q
.H)P p4! 5
:Order of Evaluation
( H)P"; >  ..q CH
H) U C @  C Q H)  h6 Z6
<!@ CH
! !3  @!< 8! CH) N<@ ( )
P !; )] 5! 3
. (2 + 3) * 4 : C8
P |" ! )] HQ(  6 b
: Associativity FHA
. ! N G e!9  H)P( 6  !C Q 8! ! N G @ gH! C Q
g9 C!M ``]! C Q C8 C Q kQ9 .(2 + 3) + 4 C8  + 3 + 42 8! CH) N<@

a = (b = c). H@9 C Q a = b = c :C8 G N!


Expressions ...!$7A
HQ)]
Example 5.1. Using Expressions
#!/usr/bin/python
# Filename: expression.py
length = 5
breadth = 2
area = length * breadth
print 'Area is', area
print 'Perimeter is', 2 * (length + breadth)

Output : bD
$ python expression.py
Area is 10
Perimeter is 14

: 0 A `$
>!( 6 !59Z C ]^9 !
 breadth >! N 2 ! Length >! N 5 !})
{(area = length*breadth) ( i8
M .)A p4 5Lg@h9 ( breadth--length ) !>N G ]^ CgG! @ F !

@ HQ 3]^ 9 ) .HQ@ G!9 CgG! eM  G GM 5 ]G
h6 8 UM( 6  .print H)] 9 U@Hg9   area (6 >!( 6 length * breadth
.print Y`/H( 62 * (length + breadth) HQ)]
! 9 H
9 6G M   W .R@ HF (6 9
 ! 9 89^!_  A b
.area >!
g T"59 < <9
8 R H YH` g m R N<@ ` M C  "; 5Qb 89
R H!< HG9 <5) M CQ3 89 ( 4 N<@ 8 ( "R( 6 6G!  n<9 Q) |" 
. !!
'Area is'

::I
expressions HQ operands d Q!/9GM M operators C Q )] 4 c

.R 9 Blocks C N<@ ))( H (
.H/ Y)] `9 3 9 (6 5 )]9 ! <( )   6

1 02,
Control Flow

Introduction ....................................................................................................................... 
The if statement ......................................................................................................" if " H
Using the if statement ..................................................................................." if " H)]
How It Works ..............................................................................................................C!Q
The while .......................................................................................... " while " H
statement
Using the while statement ......................................................................." while " H)]
The for ........................................................................................................ " for " <M
loop
Using the for statement ............................................................................." for " H)]
The break statement ..........................................................................................."break " H
Using the break statement ........................................................................"break " H)]
The continue statement.................................................................................." continue " H
Using the continue statement ............................................................." continue " H)]
Summary ...................................................................................................................d]

: 
 *
p4( 6 5 d" 4 d.h9   9 89 H C)d) !L  A (  R H( 6
 kQ9 ]R H  8! CH) N<@ C!Q G F >   . P
' Good Evening ' ' Good Morning ' !<@ HF C8 4<]! <!
 QH 4<] 9
 q c
  N<@ ; 
 i
if for -while : C8 89 (6 H n6 M N<@ gG N<@ 
 ; h6 c c!. !
: The "if" statement
h6 A (if-block N!G) H < C> h6 true   nM< ]G
. . " else " H .( else-block N!G) 9 < . @!< C>
Example 6.1. Using the if statement
#!/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:

print 'No, it is a little higher than that' # Another block


# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach here
print 'Done'
# This last statement is always executed, after the if statement is executed

Output
$ 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

: 0 A `$*
>! ) M . " Q   " 6Q ] G!" ]! . 6 R H( " 6
)] 9 ]G!" ]! .  .23  T   YM @N" number"
raw_input ().
.( C`4( 6 5@ !^ 9 ) .5 ! @ )]R H ^ A  (
d.! m  N -@ Hg9 " (  raw_input " 3 ! !< ` < g@h9 !

 (6 ( d.!   Q enter N<@ e>b ( C. 3!9 . ]G!
" >!( 6 U "  ]^int " )]9 YM @N - " M Q9 - @ H@ raw_input
gG ; q  U6Q <; Q@  C "  class " HF @ H@ " int "  M( 6 . " guess
. ( - C. YM @N<@  M <!3 6 N<@ ) YM @N - C M
R H  U G h6 . "23" T. " Q 9] G! " guess " !] 9  ;
Q9
(! ( H @ 89 H] indentation <8<  G ]G_  A <!Q 39 )@ Hg9
tab g>Z " :
@N<@ cH8 ; N! . 89 (6 indentation <8 ! 2H) H ; . <  N
! ; CQ4) C56 . " indentation level C 

block < 9 89 N  M 5( 6 colon (:) N<@  M " if " H_ d
. !G H
"elif " H @<  )] 23  ."" Q ; H C
]! nM9  ;  Q9
. if-elif-else  9 C. elif-else : if
 d@  H  9 !3"
. 9 <g! indentation ! C< C5) R H CQ3;
H @ <  H (g! gG 5( 6 (:) N<@  M else elif 9  c 23
(! Hg9 2)!< 8)
. if C. !H N!G "if-block < C. . "  if " H 9* !;
: if H 9  ! C
. . " else " " elif " ^P* "
if True:
print 'Yes, it is true'

<g 2  " " else " " elif " 5M  !H 56 !9 d  if H" 4 89 (5  Q9
5<  H R H" 4 ( GL < M T"( 6 . if H  < M ( H N
. FGH N5!9 U5  v  R H 5 89  Q9 . print 'Done' H
( "6 N 5md  ( @<; A 8 N  c5H  eG9 R H " W
3 9 4<]9  |; P HG9 4 C9 gG9 ) gG9  !< 5< T" .eGH R H
 ) 5Q  YH` ) ; Q9  H T" C  YH` ; 2<g ( C/C++ >
. ; 6  59
3 H + + / R< Umd
kQ9 (6 )UG4 ( CQ4 N .o 9 .. elif.. !; )] . 89 9 (6 CH  p
)@G9 ; CQ4 )]  AM
C/C++ /!7 9:
do it quickly) H  ! )] . 89 (6 switch statement CH 9 p
( )C9 ; C!Q ]  G AM kQ9 (6 ( ) p4 C!Q if..elif..else
The while statement ..... " while " $7 *
" while " H .true    H" < 49 ;  Y!G " while " H
"  . 9 C! " ! while " H . looping statement " n<M " N!G ! 8
" else
: " while " H)]
#!/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'

Output : bD
$ 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
: b!7 0 A `$*
U!]9 4A9 U Y!G] G!  !^  guessing !] HQ 2Q<   R H( " 6
- 9) (6 <Q6 ! - !] C   @ R H" 4 N   cG MM U!] A
: " while " H )] Z 9 " .
>!< Q . while loop <M C. N" if " " raw_input " H; M9 !
.
. while loop <M C> CH
true N " unning "
9 < d. " @!< !4 (6 @ Q9True " unning " >! CQ39 !
: A
. while-block
" >! M T"( 6    nM  while-block < T"" 4 Q9
. "running
<" 4 C G6 A " while-block"H" < 49  " true" U >!  h6
. ( H N C Q9" else-block" .A
!9" False" |F. while loop <M( 6 YH` @  else block <" 4 3
56 " while loop" <M< " else" H   . nM 56   T"

. 5  ]9 9P N)! 9 ( while loops  ; <A! L" 4
. (  N<@ 0 1 ! AQ HQ !; Boolean types N!G " False" " True"
.1 C8 U<Q4 U! 5! p! 5 nM!   8 5!Q) 5!
< p4( 6 5 Q9 H Z @  !; M @ L CQ49 "  else-block "
. P p49 while   Q9 (while statement H(  6 !)
C/C++ /!7 9:
" while" <M< "else" H N<@ ` M !; U"

: The for loop .... " for" 


-
objects L Q9 <G<) d.  ( .o looping (< 9 ( H( 6 " for"
C A ` 6 (6 C`49 C)dG !^ @ N<@ Q) .UQ9 <G<) (6 `@ C d. "C8
.9 <g! Q! @ 3 3 9 q U6Q ;<@ 

Example 6.3. Using the for statement


#!/usr/bin/python
# Filename: for.py
for i in range(1, 5):
print i
else:
print 'The for loop is over'

Output
$ python for.py
1
2
3
4
The for loop is over

"

: b!7 0 G $,$** *
<.)]  9 @P< G<G >< . @P< G<) @Hg9 !
R H( " 6
"range

) ! !


! ) (51 N!> ""i

! U9  @ Tg
! " !59 "51 <G<)  QP
 9 Q P 
`@  N` C NQ 8( @< CH) N!8 (51) @ !3  <G<) (gQ ][4321
6 Z ".! g. range 1 !9 @@ Ug   8 ] g !9 ; QN<@
) CH!8 :! i} .[31] (gQ (251) @ !3 ! `M 1,5 9^4 ] g !9
.
"{ 2 ! !  NQ 8( - A U! CQ 8(
Q9;  d. "for" <M ; !

for i in range(1, 5):


Q :
for i in range [1, 2, 3, 4]:
(  UH) @ C )  ( object- L N!> i  (6 5 C Q9    "4<
H  !
C . i (6" T M @Hg9 e6! (6< H .
" ^3 " " else. .! b 56 !L 6 "4 5 " for" <M A 
. ` 9) gH " )} "break.{C<
Q9 U
" " " for C. <M C!Q loop )< .<G 
 !L@P  >< 5
d.   " range" <. @< N !Q ! )] P C)dG L
}  . !{ Q)  9  T"54 (6 C`49 `4   .
:C/C++/Java/C# /!7 9
 + " for" 
-6 `-I +:%  C# /!7. C/C++/ G :?  E + 
-
6 N*  Java /!7 .C# + " foreach " 
- :9  M Q, + K7N
7A :
") " for (int i : IntArray  Java 1.5
C/C++ (6 9 (46 " for (int i = 0; i < 5; i++)" 2 8 e6 2
" ) . "for i in range(0,5!  6  99 (6 <M 8 FG9 8
HQ C
@.g]< Z

* $7 " The break statement " break


: break statement]G (6]  <M .!8
  "4 N <M  ` YH
 False <M )< <G  Q. C 9
!md ! !5; 
!]9 c < " " for " "while h6  C8!9 U  "4< H
] 9 " . "else

break statement I *
Example 6.4. Using the break statement
#!/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'

Output
$ 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!
Length of the string is 12
Enter something : quit
Done

: b!7 0 G $,$*
. C( 6 <.! length QHF ]   G! d.!" .9 !
R H( " 6
"quit " ] G! C.!   -M6 d. R H 
 . F 6 9 !


. R H 5 N<   M ] nF @ R H C!@ 4

. "len" <.)]  9 {6G! 56 !9 M }@ C.! gG F ! 
.  C9 " for" <M 5 ! )]break statement "
!! 8H " G2" Q
`
" G2's Poetic Python" : 5!) 5H >
 Q @ g 8!( " 6 c ])
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

: The continue statement


C M< M( < 6   9 Ng] 9 89 d9( 6 The continue statement ]G
. <M
Example 6.5. Using the continue statement
#!/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...
Output
$ python continue.py
Enter something : a
Enter something : 12
Enter something : abc
Input is of sufficient length
Enter something : quit

: b!7 0 G $,$*
 ])" . C
P N<@ 3 @  e6 T"4  ]G! C.!< H
R H( " 6
9 skip C!Q9   3 C
g  h6 HQ F N<@ ` M< " len" <. 
"4 < ( M( 6 H 9 d]9 ." continue" HQ)] 9 <( 6  ! H
.!< Q T C!@ !
.  C9 " for" <M C!Q " continue" H@ _ A
: :I *
gH! H ( if while for ) : H n6 (6 M< d )] 4
 
 4 ;  89 (6 ]  @G!^ P 8 kQ9 ;<.( continue break) 59
. functions ] G! <( )   6 . Z   5Q

"1 02,
Functions
  
Introduction................................................................................................  
Defining a Function ...........................................................................  Q
Function Parameters .....................................................................   9
Using Function Parameters ................................................  9 )]
Local Variables ........................................................................... <M!!>
Using Local Variables........................................................ <M!)] !>
Using the global statement ....................................................( !Q H)]
Default Argument Values..................................................... Z6A g) 
Keyword Arguments.......................................................... g)  4!<!
Keyword Arguments ................................................g)  4!)] <!
The return statement......................................................................." return" H
Using the literal statement ................................." literal" (6M H)]
Docstrings ......................................................................................... 89 nL
using Docstrings..................................................................................................
summary.................................................................................................... d.
: 
*
;! H )  < g@h9 ; Y!G 5 .5 ! @ )]R H ( ^ : 
M.  )@ N!G! 9 Q" . @ ! R H(  6 < T")]
.range"  len"  C8 <.  bQ9  ])
 CQ49
!9 ( () d5
P <   Q!) 9 @ H ." def" 4!<! 9  Q
C 9 ( H ; < 2Q . (:) g9 gG( 5 )! !> kQ9 5Q n6
: dQ6 FGH W (6 ; H " 8! .  T"^
:  Q
Example 7.1. Defining a function
#!/usr/bin/python
# Filename: function1.py
def sayHello():
print 'Hello World!' # block belonging to the function
# End of function
sayHello() # call the function
Output
$ python function1.py

Hello World!
: b!7 0 A `$*
 9 " . A  T" .Td@ YZ ! 2)] 9 sayHello !G  M9 
! N  <e6 Z    9 . )  9 @ >d@   A (9 {
}
.RL 5 !5 Q 5 4<] 
!
Function Parameters  * 
W !>UH  H T" .  T"5 ]G 
) cG (  9 ".  !
.  C.9 
5 G A @( G @  M 
 !>
@   . (:) g9  `4  Q9 ]
)( P C. M  H
. g p49  5gQ )@ 9
 C. NgQ (!  9 parameters N@  Q (6 gQ!)! P 5!  P* md *
. arguments N@
:  M )]
Example 7.2. Using Function Parameters
#!/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

Output
$ python func_param.py
4 is maximum
7 is maximum

b!7 0 A `$
Q 3) .( a , b) ( ( 9) "  . i printMax )9  6@ 
.HP Q@ HF ; Q9 " if..else " (HQ eG9 )]9 HP
)]A( 6 ( arguments) ({ 43} @P H Q M printMax ( )] 6
N G x e) 
! printMax(x, y)CQ3.{x,y} )] !>9 )@ 9  (8
C( 6 (p4 C!Q The printMax  . b  9 N G y e) 
! a  H
.AM
Local Variables $- ! $< *
 >P  9 gH  A  Q C. @ !> d@9 @  
g N!G "   C. local <M HQ )! !>.  Q . )A p49 .
9 (6 starting `< G<G( 6 5@ d@  < C. g 5 ! !>.>!
. )A Q
Example 7.3. Using Local Variables <M!)] !>
#!/usr/bin/python
# Filename: func_local.py
def func(x):
print 'x is', x
x=2
print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x

Output
$ python func_local.py
x is 50
Changed local x to 2
x is still 50

: b!7 0 A `$*
. x )]
! G ( NA  ( ! T"( 6
. ( 6 U@ <@ " parameter M!]
! G 89
(6 x !
>(  (  " @  6 local <M HQ x )A x N 2 ! ; ) Q9
. G d9 GL( < 6 M! x YH` 
. CQ49 p!  GL( < 6 x !
  .P print 9 (6
Using the global statement  A  $7 I *
local <M p )A 89 <H |" @<;  . M!) A N )
!
> N )
! CMG! .global statement )]9 ; CQ4 M . global ( !@ U
. global statement   )]. M
p4 C!M @ !> " 69)  . M! !> C  T"!; )]

 "N HG9 YZ W YH` UA 5H3 N>H U<@ 3 P  P " W .( C.) A
.  !>Q (6 ; !  . R H
.( < ]6 Q >! Z 9 global statement )]9
Example 7.4. Using the global statement
#!/usr/bin/python
# Filename: func_global.py
def func():
global x
print 'x is', x
x=2
print 'Changed global x to', x
x = 50
func()
print 'Value of x is', x
Output
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2

: b!7 0 A `$*
!
G @  6  global ( !@ > x 9 d@ ]G global statement

.GL( < 6 x !


]G @  5m " > h6  C. x N
: 8! CH) N<@ .global H p4)] 9  global > 8 M ;!
global x, y, z
Default Argument Values l - K$!+k@ $
*
 Z6A )]  . Z parameters 5M kQ9 CQ( 6 2W 
kQ9 (6
 M ;! . argument @
 G Cb49 ;  . M! T"5  6   A ]G!
(=)  d@ 9  Q (6 parameter name M! ) Hh9  H< argument C UZ6A
. Z6A! 9 @ H
8( 9 ; )   .constant 9>(  H argument UZ6A U! 9 !<@
. " "e6 q  .A ` 6 (6 C`4
Example 7.5. Using Default Argument Values.Z6A)] 
#!/usr/bin/python
# Filename: func_default.py
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)

Output
$ python func_default.py
Hello
WorldWorldWorldWorldWorld
: b!7 0 A `$*
Z 6 !
 5gQ  .@ !<  @ ! ! Hg ]G say 5!) 
. e6 !< ! 3@ HF ( Z6A
. parameter M! @  N 1 argument 
! M nF @ ; nM
8( ! 6 .!<  3@ Hg9 (  e6 -( gQ say ( )]6
 N<@ - (  ) N<@ argument 5 - d ULg@h9  M say !Q)
. p!. <!3 

* @* *
!  A Z6 argument 
NgQ ! parameter list 5( 6 (  H T"
<Q!  H 2<F @ (Z6 argument 9  9 CH
(Z6 rgument  9 ;
.   9 !L
(6 5@
def func(a, " : 8! CH) N<@ . position 5QZ 2G  H N G 
2HG9 ;
M " b=5)
. Y<` A " def func(a=5, b) " !9
: Keyword Arguments *
C !
(gQ |" !; e6 5bQ9 M    H Q  kQ9 ;  
(keyword) )A] " G M - keyword arguments N!G "  -- 5!G nF @  H
. 9 ] arguments  M ( c
 F T ]) )" 
 position Z ! A9
T"  9 >A N(  6 G i C5) )]   NP - : ^U  P;
. arguments
. parameters 9  ! (  ! arguments 
 <g@ gG  8!^
. arguments  Z6
 N<@  M
Example 7.6. Using Keyword Arguments
#!/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)
Output :
$ 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

: b!7 0 A `$*
argument C Z6
! 9 (a) parameter M N<@  M func 5!)  T"
.{ b=5, c=10 i} argument  Z6{
 b,c} parameter 2 5<
5 Z6A" ! . b  H 3 !" . a  H func(3, 7) P)] A( 6
. !" . c  H

(
6 Z ( 6 ! ! U a >! func(25, c=24) (8)] A( 6
U!
N<@ C`M b >!! 9 24 ! N<@ C`M c>!{ 25=( }argument
5 Z6A
 M <  keyword arguments  ]) func(c=50, a=100): i8)] A( 6
!
 @ c CH
a M9 !
 W N<@ a CH
Z c  H< M!_ ! A
.  Q9

:The return statement *


N<@   ! . ! .  ] C8  "  return" HQ] G
.< g! U
Example 7.7. Using the literal statement
#!/usr/bin/python
# Filename: func_return.py
def maximum(x, y):
if x > y:
return x
else:
return y
print maximum(2, 3)

Output
$ python func_return.py
3

: b!7 0 A `$*
({ 2, 3}  <gQ!@ P(  6 (  H HP M   maximum  
. !  <; Q Q9 HP Q
! N<@ 8Q<. if..else ( gG9 9 C!QG
. None  G  
!  9 return @   : md
!
C!M A > N]  G  8! CH) N<@ . Q C8! 89 (6 .  HQ None
. None 
! C!M 
.return  ] 59 2 ( 5  @ None H  N<@ !Z  M  C
H] G A someFunction()  @   someFunction() @Hg9 ; !; 

return
: (<!
def someFunction():
pass

. H W6 < N  89 (6 pass H] G


DocStrings *
d.  @5 " (  documentation strings " ` nL  N@  ^ U 89
" DocStrings" `]! 5!)
Cb6 C9 R H n  N<@ @G 5 i 5 4G @<; 23 (   : Docstrings
. 54<  5) 8 U<Q3
!! CQ49 C!Q9 R!H @   docstring @ N<@ ` M N ! } C9
: docstrings I *
Example 7.8. Using DocStrings
#!/usr/bin/python
# Filename: func_doc.py
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__

Output
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.

The two values must be integers..


: b!7 0 A `$*
N<@ b nHg DocStrings _ A .  <docstring < P( g! gG string
. . ` 6 (6 59 ( )  classes modules
(5 capital H M9 H g) ( 6 g)P Q C!3 ( docstring (6 QH!
 4A
. i8 gG( 6 C`4!!<  39 @ H 6 (8 gG ; Q9 . (.)g9
. !5!  U"H  C docstrings C( 6 
4A T" H  9 ;M`
b4]! F_ A) doc__ )]9 printMax 9 ] docstring N !  
. ( name belonging__to N )) !(_N G (double underscores__ !^
@ < !^Q ) . b  C!" " object " L U ( C HQ 89 " e6 *
. " classes" Hg9 n<Q! C`4( 6 "objects" L
. CQ49 docstrings  )]F CQ49 c ; 9d6 89 (6 help() . c ])
 c*
. n" 5 )< 9 ; 5ZQ  T"5 !! doc__ bM) 3  @<; C*
" . ;3 9 (6 help(printMax) : Z e6 Td@ H!  d. ;* !; )
. @G! <] q 4 e>b
]G c 9 (( h6 ".g T"59 ;3 9 nL )  5! q P
@ help() )]A C8!9 C!Q 89 ( " pydoc  P .5H 56W  P docstrings
. docstrings nF
:% *
. 5H 6( g>_     d!  9 <Q! 2 3 8 
! <( ) 6 .  )) P 89 9 n<Q ( P mQ g>9 CQ49 !
6 ; W
. Python modules h9  

6 02,
Modules

 *
  @ )] @ .   Q nF @ ;3 9 (6  !; @ )]  c

M) < A( 6 : module ! .modules !3 c!. 
! ! Q 5H ( .A R H( 6
module  ) <  23 . R 9 (6 @ )] " ! .54Q9 c!
(!  !>
. Py . 9
) 89 H ]G ( ! g ( T" .U4 4)d .o R 9 CH
 ! )C!
.^< <! U) H! )] 4 )  A .YM Cg9
: sys module I
Example 8.1. Using the sys module

#!/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'

Output
$ python using_sys.py we are arguments
The command line arguments are:
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']
: b!7 0 A `$*

H. NQ!9  ) " P( 6 " import" HQ)] 9 module sys )9 !
H( 6
]| H 89 G4 gH 4 M sys C ! . C   )] ; ! 89
. U9
(6  ! P(  6 sys.py C @ ! iMH Q9 sys  G! C ! 89 "4 @ 
(6  ! H C> " L@ <!  h6 . {U nH)} sys.path >! 9 ]! L
. !Q)d Q C ! YH` Q9 C! 9 ] GL<
'system' ` .' sys' "; @< . C ! 56 N@G @  e6  6A T" : 9:
{g9   !< }) notation dotted )]N  module "sys" (6 "argv" >!
sys.argv
Uh6 ;" . ;3 9 (6 ]G .o "argv" >  UH A )A)< P  !^ "
. sys C) ^ ! A ; N<@ Z 9 
C9.(A G
( 6 C`49 ; ` ))  C!3! L
@ H@ sys.argv >!
arguments : d8 . P gG9 arguments !L
N<@  M sys.argv h6 M 8
.  P g) ]G ;3 9 N!!
]G c IDE   g) M F @ iM9; 3 9 C> 9 arguments. L  d. ;3 H

C>9 !
6 using_ sys.py we are arguments N!G! 89 R 9 "4  @ 
N  ! arguments @ H@ U Q9 .P P python  P sys.spy C!
. sys.argv >!( 6  5]^9 89  . R H
;" . sys.argv !L
(6 argument ! L C!Q{ > " c9G }R H " )
' are' [ sys.argv[1] ' we' [ sys.argv[0] ' using_sys.py'  ) M T"( 6
. p  Q H 89 _ A . [sys.argv[3] ' arguments' [ sys.argv[2]
 md . 5 ^< (  ) ! P! )! L
N<@  M sys.path >!
sys.path ( "; ^M C N  W4 HQ T" W6 sys.path (6 H@
H ;! U TQ ;. PYTHONPATH environment variable |H > UG4"
P T"(  6 C ! b >( @<; H6 ;" 6d. . (M C( 6 ) ! <^ !
. sys.path !L
(6 !
Byte-compiled .pyc ,-*
T"  . )C9 C!Q 5<Q3 CM kQ9 C!Q9  89 >6 " HG p4  C) !
M| " H9 eH " .pyc  9 ( Byte-compiled .pyc 4<!9 N!G (   g
]G .pyc  9 <! ( " 89 C!@ 4 @ U6 M ^ "3{ ) " .py} 5 R H 89
<!Q^ 3 i @) 8 ) -<] R 9 8( ! 6 C@( ! G@ 
`!< @ G ( byte-compiled 4<! T" h6 C8!9 . CQ49 U<!@  
C< ) ! g!
.pyc. 4< (  6@ 
";  9 . platform-independent

:"from..import" $7 *

!; )]T@ ( C( 6 .sys 9 23) ;3 9 N" argv" !$< ! $ (! 7
!; )]sys C( ! 6  ]G!)! P C ) ." from sys import argv" H@
H@ )]23 @U 9 . ^< ! C C!Q " . "from sys import *"
H@
(6  5) 8 g T"59 ) R H i import H@ 5 A9 " )]from..import"
.( )!6 TH 23 ) U

: A module's __name__*
. module J @ :%  *!I   0 + $7   G /  0  module 0
 NP( ! 6 module  G ; @  9) 5
  .  (6 !C5) ;
. module  GL < C>
 .o module  G p 5G4 ( 59  ]G R!H @   e6 < C>  
. C ) ! N G __name__ )]9 UM !"
Using a module's __name__*

Example 8.2. Using a module's __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'

Output
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

: b!7 0 A `$*

!L
YH` C! ; ! b__' main__' )A " M __name__ ) C!M 89 (6 C C
. H)! P C!@ C8!9 !] G! d. U"9
: J % Modules 0 G*

. ;" C HQ 8H R 9 C .e] F N<@ ; C!Q9 )  C5)  ; 9 . ^<
. ; ; YZ ) ( 8! . .py N<@ UL @<;   e6
Example 8.3. How to create your own module
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
# End of mymodule.py

R 9 (6 T! @9 !9 ( `.  (d6 !  . eG9 C Td@ H! R H"


. .P 89 R 9 (6 C] " ! G! <( )   6 . 89
( 6  23 C ! R H U<@ C!Q " C p4( 6 Z 23 C" " !
. sys.path !L
(6  ! P
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version

Output

$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
: b!7 0 A `$*
p4] G_  Adotted notation @ )]89 3 . C @ ! N{<  g! 59 !<})
p4notation . P
  ` F <Q Cm @< p " 5<W ^! "( 89" Q 4Z

from..import*:

Here is a version utilising the from..import syntax.


#!/usr/bin/python
# Filename: mymodule_demo2.py

from mymodule import sayhi, version


# Alternative:
# from mymodule import *
sayhi()
print 'Version', version

mymodule_demo.py. R C8 mymodule_demo2.py R

: dir()  *
 ( 6Q! T" . C ! M 6Q!< !L
C!Q dir() 3 !< .!; )]  
. C( ! 6 6Q! classes Hg !>
 @ @ . C( ! 6 6Q!)! P! L
 Q (56 dir()  )! C; ! Lg@@
. (M C( ! 6 6Q!)! P9 !L
 Q 5  argument
: dir  I *
Example 8.4. Using the dir function
$ 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()

]'['__builtins__', '__doc__', '__name__', 'sys


>>>
* 0 A `$ !7: b

(6H  )] dir! C! G . sys! 


 !]Z !L Q( !. 5<@ C
Q9
! ])9  9 dir ! 9   56 Z (  Q
 !LQ
!! <! C. (M
(6 dir md C" Q9 !
C!Q >  " "a) T !
NQ9  dir -M49
) _d 
! 6b N p49 !L .{a} )A "M9  ! (6 >!< HG! C(M
])9 @H " "del)  pQ" >   (6 R . dir
del N<@ md" THQ ]G "M ) > Q9  @! C!> ( (6" T "del a" : M
A!; @< N!  g C   N!> a   5 @< NdF
CH
* :I :
! C  P 4! 5  ]9  L! @ )] 9 (6 5 . 3! H) ( (
9 8 8 HQ @< N! <^ .
   ]G " T! <^  ! <^ ] 9"; .
!6<( )  kQ9 <Q!4 ! !5( @." data structures" N

$7 0$ : "  02,


Data Structures
Table of Contents ...................................................................................  
Introduction ........................................................................................................... 
List ........................................................................................................................!L
Quick introduction to Objects and Classes ......................Hg L @ UQ   )
Using Lists................................................................................................. L)] 
Tuple.............................................................................................................tuple L

Using tuples .................................................................................................................
Tuples and the print statement .......................................................................................
Dictionary.......................................................................................................... 
Using Dictionaries ...................................................................................p )] 
Sequences ...........................................................................................................C)dG
Using Sequences................................................................................ dG<G!)]
References....................................................................................................... 
Objects and References ...................................................................... L
More about Strings................................................................................ C!3!^ @
String Methods ..............................................................................` C)dG 2)
summary........................................................................................................... d.

 *
. THQ9 .Q H kQ9 C! 5!{ 4<! H m}C 3 )) ( H C
-- 89 (6 3  H C d  <` H! @ 3 ] ]^G (56
M CQ3 5  5 C )] 4 ) .dictionary  tuple !L
list !L
. C5)
list:  

!Llist <G<) !; ]^d8!6 <` Q! @ 3 C!M ( H C :
!6  <Q @ 56 ; G< !L
(6 4 c ` !  C5)  P " .!L
N6  H
!6 9 <6 b 89 (  6 G! L
(6 C`4 g) (6 `@ C ; C!M!@
59.
9   3!9 .!L
M  ; 89 54 N [ ] Q9 )
9 >(  H Q! L

 H" M b ! "| .!L( 6   H @ iMH  6Z !; !L

T> ! { "  H<!< <>}!> 9


9 ! ( L  M.
{CL`4 }Hg L< UQ   )Objects and Classes

 q N . c (
 WObjects , Classes >!] G  @ ;h6 @U 9 i G

L;  h6 5 5 d8 C
!  UObject " i <`4< 9 "class {|4} int ;!( 
6 .
help(int) C ! .Cb6 C9 L  54 class )]d M!  C8 2) N<@ C!
" |4 T" . U 9class T"5 L @   ; e6 ^P T" 4! Q) !; . e6 "
class |4 6 F 89 6   8! CH) N<@ list" .!L 5 N @` 6Zh9 ; Y!G ("
: {>` T" }8! CH) N<@mylist.append('an item') `< G<) b) string !L
N"
mylist" _A dotted notation 2) N { <  e!) A }objects.
|4 class   b 5 !  fields ;< -]! 6 5 )]A ) > cG (
; @   2GM6 )!P / !>T" !; )] .e6 |4object b M .|4 <;
e!) A 5<@ d. 5!   dotted notation 8! CH) N<@ mylist.field .
: @
I *
Example 9.1. Using lists
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist), 'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

Output
$ 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']

b!7 0 A `$
>!shoplist (6 . G N 2 -] G !L
@ H@ shoplist ` C)dG]^ 9 
strigs ;( 6 !9 !L N<@ L 6Z !; U  " 5 ( )Q)! P
.P L  N@ A.
<M )] b  for..in" " (! L b c ; 9 A q . H! L
d. <
<G<G! sequence <G<G!!]` 9 }
 ) . sequence. nA G
(6
" H@ 5( 6 "" <6 ]G_  A " print"
H@ C Q9 g)P C4 @ <Hg!
print !5!^ 3< Q3 gG9 5 ; CQ4 MH
FHQ 
T"" .
6 F )]9 !L
N 9 6Z9 !
Q9append N list object  
nH) !
!9 FGH9 ;! L  M HF nF @ !L N U6Z CQ49  
H nM  .CH

H@ nF @ !Lprint H  Ug9  5QHg9 (  .


F )]9 !L 29   sort Q A 5G4! L N<@ )< A ; " 54 .!L<
` C)dG C!@ F @ <] " -- Q!! Lstrigs >< <9
L  9 UQ "  .
` C)dG strigs9 .
" H )] nF @ ; nM .!L U  G( 6 9 ( 5 @  del  . "
" H  U!  L( 6  "H N  del!L  U6"M9 ". H U   M
]G M( 9 !L Pdel shoplist[0])0 Q H 89 )" .(
nF @ 5 N 2)A C Q  c list object m help(list)C4)! A .
: Tuple*
@ Q tuples. tuples CQ ;! A strings ` C!3 C8 9 5 A L  C8 Tuples
AM( 6 ]G  @Tuples .( )
P C. d`6 59 <`4  9 M nF
 tuple ! @  3   9 4 ! - ]G! M  H 56 ( 
.> A  ]G!
tuples I
Example 9.2. Using Tuples
#!/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]

Output
$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin

b!7 0 A `$*
tuple F N<@ ` M< 5 ! )]len   M . H tuple N  zoo >!
i new_ zoo N  M T" C q. ;" sequence <G<G! ( tuple N<@ b" 
N H CQ49   ! M kQ9 N<@ new_zoo tuple  M ". <> YH` ! zoo
tuple C. tuple _ d  P
N m9 ,. ! zoo cH<  ( M 2
5 4 A
[ ] Q9!
P C. Q Z M nF @ tuple ( 6Q N!  
H N   gG .indexing operator )54 C @ N!G "  . lists L(  6 T<Q6  UH
M9 new_zoo tuple (6 i8 H N !   new_zoo [2] M9 new_zoo (6 i8
. )< P 54  3!9 YZ " new_zoo [2] [2].
myempty = (). C8 ( )
P nF @  W4 Tuple :Tuple with 0 or 1 items
(  )A H Q9 <6  ]G M @<; .FGH T"59 p  9 59 tuple ;
. HQ C. object C gM!
P 9  9 tuple 9 4 ! 89 h6 ;"  H
.2 H! b tuple ( ; Q c singleton = (2 , ) M @<; d8
!$ /!7 9:
tuple N<@ nHg  P p4 . 9 (6  ! gGH W L  d8!6. 5 4 A !L
C.! L
H@ e6 Uh6 8H9  P n<Q  H6 . & tuple C. list list C. tuple tuple C.
. Z !( 6  C " .o object L)] 9  ]^objects L@

: Tuples and the print statement*


:8! ; " .print H tuples ( QL A!Q)A 8
Example 9.3. Output using tuples
#!/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

Output
$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?

b!7 0 A `$*
 H tuple 5< ^  5QH Q 4)] 9 `< G<) ". ! print H
N<@  !  4 ! .Q g9 RL UW (6 ]G 4 ! .4 <! U9g!
<9  9 N<@  M 23 tuple .MM`@  %d strings ` C)dG< %s W
. m p4( 6 4 ! T"5
tuple (6 A H) !> " A 9g "A %s ]G i !Q)_ A
.tuple (6 (8 H " age C C9! %d ( 8 
C.< G<G T" ! CL9< ` G<) N tuple (6 9 C M U  89 U<!Q 
. < name >! @
! ZQ) %s ".4!
string 9 2@d 8 23 R 9 <> C5G CQ3 print H< )]A "
.q N <Q6 !  C( 6 C 4! Q) 23 U ! . P nM
N C!Q " .;<
( H9 Q 8H .%s   !; )] c
 mQ
  G b " i UMM` 4 ! g@( 6 2W 
; .
P
. ;3 9 M
 A --  9 U< % ^  5QH ( 4]  ! G print (8 H( 6
.`< G<G( 6 (  @     6 e6 C!Q " .
P
*

U!) U6Q nF @ -]` d C4  @ 3 !; i   @ 98!9 
unique 6  23 4! 9 !<@ .(C4)(  )A )Y4!  M d8 . 5!)/

. eHb9 )A p49   ; ]`MM < Q N<@ ` M !; A U i


ojects   !; )]Y4! (` C)dG C8 ) e6 9 ojects !; )]U@<!
. Y4!< gG9 ] ) G A >( H U  9 ;< <>   !  9
 9
_A d = {key1 : value1, key2 : value2 } HQ)] 9 (  6 T  !" Y4!
"C <6 nF @ d`4 5G4 P" :" g nF @ <`4 !/4!
. { } Q3!
A( 6 C.
5H ;<@ Q) Q H .2 F  5 cG (  6 key/value "
. 5!Q) CH
;G49
. "dict" Hg instances/objects L/<8  HQ 5 )]9 ) p 
Q$
I *
Example 9.4. Using dictionaries
#!/usr/bin/python
# Filename: using_dict.py
# 'ab' is short for 'a'ddress'b'ook
ab = {

'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']
# Adding a key/value pair
ab['Guido'] = 'guido@python.org'
# Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name, address)
if 'Guido' in ab: # OR ab.has_key('Guido')
print "\nGuido's address is %s" % ab['Guido']

Output
$ python using_dict.py
Swaroop's address is swaroopch@byteofpython.info
There are 4 contacts in the address-book
Contact Swaroop at swaroopch@byteofpython.info
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Contact Guido at guido@python.org
Guido's address is guido@python.org

b!7 0 A `$*
4! M d. key/value  >< . U
 nH) )] 
 "9 ab `  9 !

eG9 2_ d tuples. lists @ d( 6 }


! indexing operator )54 C @ )]9
. ;" p  <
N <  indexing operator )]nF @ FGH9 key/value  b!
. Td@ !" M( 6 Guido < Q6 ! U )
! 4
indexing   M FGH9 M ." del" H)]   9 !/4!! "
T"( 6 4!< <9! U! 6Q!   cG ."del" H N ! ; 4!  operator
. <!Q
!L
Q (  items method )]9 (  6 key/value C N C` ; Q9
N TG " ^ 2MG .!9 @ H 4! H  M tuple C i tuples
.for-block <( 6  T" Hg  for..in <M)] 9 C C9! Q) !>
class has_key F N in C>!)] 9 key/value    6Q !
help(dict) )]9 "dict" class  g< < ! L N<@ dFd nL   gG "dict"
:Keyword Arguments and Dictionaries*
nH)  ;9 ](  6 keyword arguments c ])
 c _d .o Q N<@
@  Q  9 !L
(6 ;<H
M key/value ( ; 6 6 e6! p
c ])
(6 symbol table N!G  )  N   4 3  C.9 !>C>
. (  `! !Y<g`
:Sequences :1-1 *
56  <G<G!!   ( Sequences <G<G!! N<@ <8 ( strings lists tuples
(6 UQ9 9 2<  Y () 54< ( @!< G<G!!< GL! G]`  
. <G<G!!< ^ G<G!! M QG  Y " g @!< H <G<G!!

:1-1 I *
Example 9.5. Using Sequences
#!/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[:]

Output
$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
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

b!7 0 A `$*
<!@ U N<@ U  b " .<G<G! 6 @ N<@ ` M< 54 )] 4  A
C9! H 89 ; 2<3 ) Td@ H  ] [ ! 6 Q 9 <G<G!<  @M9 c!
!< .A
A H 2<3 shoplist [0]  .0
A @ H 89 " . <G<G!( 6 UQZ !
shoplist <G<G (6 9 H 2<3 shoplist [3]
 shoplist [-1] ".<G<G!! 5 2GM UM T"( 6 H<)   @b 54< !
. <G<G!!( 6 9 .o ( 2<3 shoplist [-2] < G<G!!( 6 .P H N

P -.- 5<< G<G! ) M nF @ ]G slicing operation g@!<


c!

() 54  @!< Q9  N UH  P_ " d . [:] Q9 )
C. g9  `4
. ;" cG ":"  )g  .
 A " .5!Q)9
Q9) (8 Q M U H "Z ! N  g( @!< 6 ( g CH
) P

9 H) 89 h6 M W  @.M T@ 
 "Z !< 56  ( g
@ H Q M @<! .<G<G! 5( 6 
) 89 h6 ( 8  
 .<G<G!
QHG 56 5A Z   b H Z d8 . 5A Z CH
(5) H Z
. <G<G! M
@ 
  2 Z N 6Z9 1 Z ! 9 <G<G! Qg
Q shoplist [1:3] "
<G<G!] G Q shoplist [:] C8!9 . Q H " Qg
h6 (9 3 Z !
. 5<!9
8! CH) N<@ .<G<G! 5 Z <! HG
 A] G .HG Z ! g b!;
! (b A U <G<G!( 6 .P H( 8G (< G<G! Qg
Q) shoplist [: -1]
. .o
!; iM9 4 iM! . (<@4 89 G4 )]9 M T" 4 4<] 4  
p49 !3 strings lists tuples C> ;! ; dG<G!( 6 mQ ( . 6 RL
!g
References
!U(  6 object C8! A object N A  !> A  !>N G object `  @
L U6 ]^i  H!^  3 ; N ) !>  !NQ!"
. object N) A binding e9 N!G "  .objects
N M ( references 2HG9 n
 !   A " n<9 Q N M9 cG  !@
: ( 8! ; Yb . 59 <@ N<@ 
Example 9.6. Objects and References

#!/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] # I purchased the first item, so I remove it from the list
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
print 'mylist is', mylist
# notice that now the two lists are different

Output
$ 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']

b!7 0 A `$*

5G4< Q( 6   mQ . ! L] G CQ3 ; T "N M "P


(MM`@ P C8 gG9 L cG) Q! L dG<G! A @<; <; h6
g] @!< Gslicing operation !d .o ) N ) ) !> 3!9 e6 c!
.]G C!Q
  "2@! ! N" !  56 U L N .
: !$ /!7 9:
"$?
 $- A
 J$-G *D I1 oND k @
F-p $ D ! slicing operation 0 A
. -1-1   I1
strings $2D 0 :1  G = *
5@ U6Q !  !^ " . 9) c
( 6 C`49 ` C)dG CQ49 

b ( HQ ` C)dG Q C G objects ^-M6 ( C CQ4 2)A 5
G! Q N -!
sjrings ( ! R H( 6 5 ]G ( objects class) str T"5 4! 2)P kQ9 .(
m 2)A T"!  < L
N<@ ` M< .( 8!( 6 N<3 |4help(str).
Example 9.7. String Methods
#!/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)

Output
$ 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

b!7 0 A `$*
` C)dG 2) 8   stringsnF C!Q C.. Startswith   6Q! ]G
C>! .gQ!!< 3 H `< G<G cin ^NgQ! -   -M4 ]G
.`< G<G.
Ffind (6 NgQ! - Z 3A ]G string - N<@ 8Q( 6 3   -1 @
|4 . 8str `< G<G< G<G! 9 e9( 6 @9 UF b 5 string 9 M 54`9
<G<G! 9 Csequence . 5 < `  G<) H Q
:I
R 9 9 ) )) @ T" H C .C`49 89 (6 3 ! H C) 9 !

 Q 3M9.
Q( 6 R 9 9 `! 4! <( 6 ) (  6 89  ))8  A
8H (M.

!(A 02,

6 + c !K - -N 0


Table of Contents................................................................................   
The Problem ................................................................................................... -N
The Solution ........................................................................................................ 0
First Version.........................................................................{c!1- } F k r
Second Version .. .................................................................................$6 r
Third Version ....................................................................................... 6 6 r
Fourth Version .................................................................................... A !r
More Refinements ...............................................................................* = 
The Software Development Process ........................................ $/!7  ?!$- G
Summary ........................................................................................................ :%
Q ^A T" ! 2) ( g N<@ m ) <( q 89 > 4<] ^c4)
.4 (A "R H 9 `! nF @
-N *
. ! 5! 4<! ! F] G C!Q9   3 9  ( N!<
C<M C< .CM @!< H  HG9 6<  Q cG gG9 < C " W
]G Z )  F 5]G ( ) 4<! M  ! 8! CH) N<@ .< g!
UFA] G( 6 5   ]^U !]^UFA
T"( 6 .3 9 C!@ 4  P! L
^539  .3 9 !` YM C9 <! C<M Q9
 p4 U  A ;<Q !` C!Q9 c!
.C!Q9 5 
4 9 ! L h9 c!
M
.2F  " P G ] UF U -] C -- C!
.!L
N6 M F] G 5 C!Q ( P 4<! .1
.(FA& G< pL C( 6   ]^23 FA] G .2
.> b < (6 >(  H . G! 4<! .3
.(M c
! & b> b! P ) .4
! .p / p )
Q(  6 (Z6 C9 !zip ()  P] G M .5
T 4 R H  !; )] U @<! Info-Zip program R 9 ] (  )]G!
.9 ]c9G U arguments 
  !NG N  A g) ;<! U! F
*:0
. CM" 4  HQ  " 2 ! G q 3 9 !` !

First Version 4 r
Example 10.1. Backup Script - The First Version

#!/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
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

Output
$ python backup_ver1.py
Successful backup to /mnt/e/backup/20041208073244.zip


  ` ! h6. <) C9 C!Q C 3 9 H]  i  H.A( < 6 q M
. R H( g.A )bugs   3 9 YM` < N A @< G6
b!7 0 A `$*
time os ^< ! 4G M. T g]6 g.  N   `! C M9 !
_ d)
target " C ."source" !L
(6 F 5]G ( ) UP 4<! M  .)9 !
"
P" ) target_dir ">!( 6 M! " UFA 4<!(  ]^ ! Q"
. time.strftime () )] 9  2<3 " c
( M & ULh9 > ) b!

target_dir C( 6 )]^.zip  9 .b) 


CM) %Y 4` . Td@ !" R H( 6  ( )] C8 4" . time.strftime ()
. < 12 01 9 
 @54 9 5 5<M CM) %m 4`  9 G 5<M
[Python Reference [ 8H (Q !C( ]6 5<@ 8Q ! 4 ! T"5 < ! L
(UG4 M N<@ p  )C_ " !A .;9 ] Q(  6 89 ( " Manual]
( tuple 5< )]9) print H( 6  ]G! 4<!
Q  9 e9 C!3; H( " 6Z C>!)] 9 target > b! C ) C!Q9 !

.T"49  ) P! b ( zip_command : `< G<)   .   Q
(   6F p 6F) C N<@ U<> nF @ C!Q  A   " 6Q ;!
zip  P N]  G q   ]H ] kQ9  M U ]G " zip  P
N<@ }  recursively C!Q zip  P M r ]quietly 59 C!Q>( H
i A . 9 !3
  .;"@ 4 UA C. 4<!@ 4 UA C! >( H{ C4)P
@ H T> ! b! P) 9 @ H ]T" qr ! ng(
` 6 M!! 5
UF )]9 <!3 C. source !L
M M .F 5]G9 ( ) UA 4<!! L9
. 5  )]4 CQ49  ( C!3 b join
0  Q C( 6 m C. C!Q !   os.system )] 9  P C> .
. g] 
 Q U6 A 39 <!Q c!
C " cM3 c<6 UFA] G 9 H) )@ Hg9   P 3 N<@ @!
!!5! 4<! UF] G C!Q c9) 9 !
 Z !( 6 
: D  I1 9:
.( 6 d<
  23  C) < P target C source !L M !;
C8! (\) backslashs ]G 89  C`4 C)\( backslash ]G!< ( 
! escape sequences 5 C)d)
N<@ .raw strings ]G ! @<; escape sequence )]9 5G4 F C8! @<; ;"
-'C:\Documents' ]G A ' r'C:\Documents' 'C:\\Documents' )] 8! CH)
! \D :  */ escape sequence < G<) ]G c
( ]G .4<!< F] G" . !  U ! )] (FA& G< c9) C!Q9 !
q
C> ! N U
 nH) "M N<@ "4 !< F )]9 M` p / p
. 3 H <  C> < N!G "  .( 6 c
( 6 (FA& G R 9
8! CH) N<@ .
 c !  ! C!Q A NA R H  )@( YM C9 Td@ R H C!Q
&  U9( 6 g.
 c YM C9 R H  `! c C
   
. ;3 9 YM` gb) < `! N Q @<; Q) 2) C9

: $6 r*
N<@ C!Q U! N U<@ GM kQ9 . ! ; . C!Q cHG NA U]G
. 3 H <  N!G "  .N ) N<@ Cb6 M
C.9 <!< ) time )]9 -- <!! G Cb6 (  5L49 Q ( GM T"
FA]; G !^ ( . UFA] G C! Z C current date &  C
89 `
 4<! )! F  ( .  ^ .5 C5)P! 6 "   g9 5 ]^
C!Q9 c!

c   5G9 Q @ G) <`4! UA ( .   ^ .g T"59
. ";  F] G
 ]" c e6 C "  C @ F] G
Example 10.2. Backup Script - The Second Version
#!/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
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# The name of the zip file
target = today + os.sep + now + '.zip'
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:

print 'Successful backup to', target


else:
print 'Backup FAILED'

Output
$ 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

b!7 0 A `$*
C C.( M)  9 C   nM > ( .UG4  R H " 8
]  G UQ` M6  W h6 .os.exists )] 9 UFA] G< pL
.os.mkdir
(6 '/' ) U; 9 ]C> m 6 C`4! C( gQ 56 - os.sep >!_ )] A
M T" A9 Os.sep )].  C> m( 6 ':'(  6 '\ \' ) p p
.m T" H@ C!Q A !M 3 9 CQ3) H C9
: 6 6 r*
8  @    FA& G 8 C!Q9 c!
c  @  C!Q 8] G
CH) N<@ ! C c F] G C W 9 n4( 6 9 Q  UFA& G
>T" Z  @ @ 8! R H< GL > kQ9 c<Q(
 6 8!
P ) N<@ ]G! n<Q 6 nF @  5G9 UM ! " . > b! P)
.> b!
Example 10.3. Backup Script - The Third Version (does not work!)
#!/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
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' +
comment.replace(' ', '_') + '.zip'
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

Output
$ python backup_ver3.py
File "backup_ver3.py", line 25
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax

b!7 0 A @ `$
89
 " m( Z A c9G( Q > ! g. !  89 .!C!Q A R H"
eHb H N .T@ g] @ ! "  H] "; 89 U 
( g]_ d @  .T
. gG ; 3 9
9 M   p   g) N G(  
 g! gG  
 Umd!9
gG( " 6 operand 9G  9 (+) C>! 89  6 )) .Q  !gM
d ^  A (g! gG M "  ! . C!Q C  Q A U( g!( 9
C!Q9  ;" . !gG 5( 6 \ backslash 4<]< L! F)] 9  ! gG( 6
bug fixing g] d N!G "  .3 H YM`"
A !r*
Example 10.4. Backup Script - The Fourth Version
#!/usr/bin/python
# Filename: backup_ver2.py
import os, 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
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
# Notice the backslash!
# Create the subdirectory if it isn't already there

if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

Output
$ 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

: b!7 0 A `$*
<Q 2@ G .3 U]G( 6 5<!Q9 !
(< Q4 GM d. (b!! @  q C!Q R H"
d.! F YZ G | U9 C.
 CQ49 ]G!   6Q  raw_input )] 9 ]G!
 (F  3 c 5<Q)  2HG enter 4 N<@ e>b9 ]G!
 .len )] 9
. CH
U9 !
 C!@ (6  Q9 (  >
.zip A CH
e6 > b! P) 9 nM< n<Q" 56 n<Q    N<@
T" 4<! )! C8 A ;"6 underscores __ <4) n<Q( 6 G! H)_ d
. 89 C5)
D$1 *= 
N<@ . GM< 3 !L    ]G! mQ! Z ` 9 C!Q c9) ( Q9 
YH` ;3 9 CQ3 v  ]M ;! i R H< 5) G 6Z !; 8! CH)
.   8
N C ) . A g) N<@ c9G N <! 6ZA P 4<!< Y!G  .P GM
extend )  F )]9  ( source !L
N 54b gG sys.argvoghg !L
;
. list Hg 6  ( method

@ U  P  ^ ; . zip  P A9 tar  P)] 9 cM!) ( R H( 6 9"5! P


C
  FA] G )@ 8 YH`( FA& G YH` gzip 2 N H tar ; )]
 P . 5G9 ;" .tar.gz 4< C Q WinZip h6 ( 6 P )] " . !3
UH8  c U<!M ] ( G! ! . p /p !m mQ (6 (Z6 C9 tar
.;"
:( C9  P ) q
tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir))

.T MZ ]
.  creation N  -c
.talkative  b 8  23  P verbose N  -v
.U >( )]H " gzip <6 N  -z
)A p4 C!M  .o < CM CM>( H U P(  6  force N  -f
.CQ49
N<@ .UFA] G excluded QH) 23 ( 4<!! )! L
!b !< " N  -x
FA] G( 6 ~ U5! 4<! )! Q <!( " 6 ~* M ;! 8! CH)
* @**
N<@ tarfile zipfile ^<)] ! 9  ) P "  C8 < b4! g 8
b H! T")] 9 .CQ49 5  ! ; )]Q! 89 H ^C 5 .(
m9 g.; 4< C5G 5A ! Q U N<@5 )]9 Y` A ( os.system )]23
.5 )]9
8 ; HQ " M9 !<Q WA F& G C!Q os.system F )]c 6 ;
.(4! 9 b 4 M( 6 5 !3 CH
 54   C9 eG9
:$/!7  ?!$- G* .
M N<@ 5`]< ! C !T" h6 .3 H 9( @!< 6 4<]! C !9 !

q
: (
What (Analysis ) ....... ( C<M  ).
How (Design) ........(!`  ).
Do It (Implementation) ......("4 ; )CQ6 .
Test (Testing and Debugging) (g.A YM` H. )H.A .
Use (Operation or ( )] ) @!< .
Maintain (Refinement) ( GM ` ).Deployment)
*@**
 C<M9 
FA& G C!@ c9) (6 TQH " A ( R H 9 59 N ! g
! C!Q U < R H )] . YM` H.A . R H< gG9 > "49 9 .!`
Do It-Test-" ")]--CQ6 ": T"(  6 !)  ^  Z q .


! NH A  ! ^3 H " .< g! M N<@ @ !P "Use
" Software is grown, not built "
:I
T" C8 9( 6  ( 4<]! C !89 (6 ] 9G/R H C!@ 4 
 YH` ; NG N C`4( " 6 <Q6 !<8 ;G49 ;3 9  4! U 3 !9 .R H
" object-oriented" L 3 H! <() 
} 6. C !C N<@ @ db6 89

!NG 02,
* $D  /!7
Object-Oriented Programming
Introduction ............................................................................................................  

The self ...................................................................................................................."


Classes .......................................................................................................{Hg|}4
Creating a Class............................................................................................... Hg
Object Methods ............................................................................................ L F
Using Object Methods.........................................................................L F )]
The __init__ method............................................................................... __init__ F
Using the __init__ method ........................................................... __init__ F )]
Class and Object Variables .............................................................. L Hg >
Class and Object Variables..................................................... L Hg)] >
Inheritance ...........................................................................................................
Using Inheritance .....................................................................................)] 
Summary ............................................................................................................d.
:
*
.H9 2@d ( H C  3 9 !`9 !
 q N 3 9 !( 6
;3 9 m . F .procedure-oriented 5 ! L 3 H F "N!G
L 3 H ! N!G "  .object L9 N!G! 6 Q 54<> H 4  9 !3"
 H R 9 9 @   A kQ9 (6  UA U3 H !; )] c
 mQ (6 .U
. U  L 3 H !; )]  5 2GP CM  "
@ n<] Hg6 .5 ! L U3 H< GL P ! HQ objects L Classes Hg
@ !  ; > U ; N<@ G
P  .Hg< 8  L HQ i 
HQ ( ( !> UMM`@ A
 !> ( ]^ N (  int YM` Q
. int Hg( objects L )A
:*C/C++/Java/C# /!7 9:*
A CH
) 6 C++ d]9 ".(int Hg ) L 5 N<@ C Q UMM`@ A N U_ d
. class Hg  C4 !^ help(int) m .CP L9 ( UMM`@ A i (1.5
/!7C# Java 1.5 54 UH U i 5 6   P ; 3) boxing unboxing
N !> ( !( .L T" N ( !( UQ)] !> 9 H ]^ L< !
N)]  ( !( 9 U4 5 b 5   L< ! . fields  N!G L Hg
n4( 6 @G 5A !5 M<g`! T" .Hg" 5 methods 2) F N!G T" .Hg
Q! 5< . L Q HF N <; ( !( 5(  6 <G (  !> ( 9
.Hg <; 4 5 N<@ 5 !  F  M
5! Hg instance/object L /  N! !( 5 C !  @ M
.(  N<@ Hg > M!( > G (56 .5G4 Hg N !(
(6  Hg F M .class keyword Hg< ( 3M!)4!)] <! 9   Hg
.<  m
The self * 
(6Z ) 5  23 5 ; -- Q ]  M  6 Hg 2)P 
5  ) method @( G  @  H" 5 !
(gQ A ; !L 9 9 N b
. self )9 NmM 5h6 4A 2G U L N  M! " !> . 89 

 9  .o ) -- self )] G  9 N  H T"5 ) g@ !; U W


N 6 U9 Q; ) 3 H
--Q ))] A  !^Q  . HQ N
. self ]G c@ G ( ! U< !  g| 9) IDE !]`` R 9

*C++/Java/C# /!7 9:*


C#  + + this (r C++ < + self !(]  A 6 + self 7G

<8 P . 5 !


g@ N M9 cG c ! self (
! gQ 89 @<;  
 @ myobject. N!G Hg T" 8 myclass N@ class ; d8 C .MZ P " CQ3)
89 nF @ L< 5< M  Uh6 MyObject.method(arg1, arg2) : (< ! L" 5 method @( G
self -]  C " - MyClass.method(MyObject, arg1, arg2 N
` M< F M N M9 ^A ;h6 argument " . A F ;  U b( Q"
. self argument N<@
:Object Methods*
CQ49 
 classes/objects >   A  C8 
F  M  5! self . (6Z
. ; N<@ A8 ) q
I *:Object Methods
Example 11.2. Using Object Methods
#!/usr/bin/python
# Filename: method.py
class Person:
def sayHi(self):
print 'Hello, how are you?'
p = Person()
p.sayHi()
# This short example can also be written as Person().sayHi()

Output
$ python method.py
Hello, how are you?
: b!7 0 A `$*

 self _ A . C!Q method !G! sayHi d Q " . A parameters   ^


N<@  Mself .  C.9
:The __init__ method*
UF )  !>^. 89 HF (6 . ! 5 ( g )! Q__  init__
q.
F__init__Hg< (!! L C!@ 3!9 C!Q . 59 |  5 CQ4 4 g T"
U< !^4G F_ A .;9 ]L ) underscoreU5( 6) A 9 (6 !d__ ( .
:__init__ method I *
Example 11.3. Using the __init__ method
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
# This short example can also be written as Person('Swaroop').sayHi()

Output
$ python class_init.py
Hello, my name is Swaroop

: b!7 0 A `$*
F M9 !
__init__ 2 N H  )H" ) . Fself   .(TQ!
b N!G  C  3!9 name .)A p4 C!M 5 W 4<] _  >A .dotted
notation !59 4  Y!G .
F @( G A _ A ; P__ init__ !9   arguments )  C.9
 ) Q9 class  n<.  @  instance T"  class T" " !>^ ] .
g.
C )]N<@
M q self.name F (6 N<3 (
 F (6 sayhi .

C++/Java/C# /!7 9:*


C++/Java/C# (6 constructor !< 

__init__

F

: Class and Object Variables*


(6 .59  ]H ) ^ A L Hg 4 9 n<Q^ 3 CQ49 
 nH) 
!Z M )!P T" . L Hg )! W49 gH  ) > @cG 5

. e6 L Hg T")
( object variables

L > class variables Hg > --  M @


. !<; <!>- (  N<@ - L Hg c ! QH `

]G  ) A .Hg T"5 (AM )L ! d.  C!Q 5 NQ (6  Hg >


. b .A AM( ! 6 > " pQ Hg > N<@ C!Q9 L @   Hg >
U L C UM T"( 6 .Hg( 6 "object/instance" 8! / L 6 C 5<! L >
(6 )A p49 "CM A C 9 eH A  cG 5 CM U9 . ]G
. 5!56 C5G CQ3) 8! " .Hg p4 4<] instance
Using Class and Object Variables 
7? !  $< I *
Example 11.4. Using Class and Object Variables
#!/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.'''
print '%s says bye.' % self.name
Person.population -= 1

if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()

Output
$ 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.

: b!7 0 A `$*
Hg N !( population  L Hg > QHF H (6 @G U C F 8 "
( 9( self )]9 G ) L N !( name >! . Hg<  >HQ " Person
. L< >
_ A . self.population p Person.population " population" Hg > N" 
)]9 L ) > N  M ! Hg( > 4] ) HF >!) A p4 C!M L >
. L > Hg > 9 eG9 d."  . L9 ] g( 6 self.name
^ @g T"( 6 . name Person M< initialize C!Q C
!QG F __init__
9 _A
L C M self.name 
_ d "; . 6b YH` Person   i 1 !9 population
. L > QHF N
N@ ; . e6 self >!)] 9 L p49 ] g !> N<W  23 U"
N !   . g "; Hg< docstrings  )]b  R H( " 6 . . 
docstring g Person.__doc __ )]9 runtime C> c
( 6 class docstring
L @  ; N@G (__ del__ . . F  __init__ method C8 . Person.sayHi.__doc
 G h9 FGH9   g T"( 6 . ^ "3! " Q) @ m N U ) @ ; Q9 U ! )]A. ! N<@ 

. 1 !9 Person.population
F
. 9G< 8 P( 6 T<!Q) " del H

]G e6 ;<@ Z 9 ; C!@ . C!Q) g T"! Z p ]G W L @   C!Q __del__

: C++/Java/C /!7 9:


@ Cclass  !@ HQ (H @ N 6Z )public C methods (6 <] HQ
__ < ^4) F)] 9 )!P H] @ G cF "W   8) . 89
C8 .__privatevar . !
5 CQ3 <@49 )A C 89 ]G . private variable.
_ <4) F9 YH` 23 L Hg C. e6 C!QG > C ( QH!
 4A h6 "
underscore  @ .P)! P ! public CH
]G ! classes/objects.
__ < !^4G F L9 )  @89 H cG 2GM6 
4 T"" double
underscore prefix (
Inheritance 
o d. U<!@  ; CL) . !  Q) @ 5 ! L 3 H< GL 6!
. Inheritance mechanism 
; 4 . Hg 9 (@6 pL 9 
d@ nHg U N<@ Cb6 C9 U<] !
G) A C8  !-L`] kQ9 5 . <( 6 dg<! Q! Q9!9  R 9 9
  ` !<Q!<  !<Q  2 C8 Q -L`. ;" 5 .  Q
. H<g<
Q   . 6Zh9  !53Q C Hg< G @ !; 
HF h9 !  Cb6P g . d  P " YH` Q ). <G HF C N 56Z
NP Hg T"  student HF teacher HF CQ3 Q9 SchoolMember N!G  
M ; ! Q9 . Hg T"5 sub-types @6  MH`) .o NQ!9 . (SchoolMember)
. sub-types (@4 P T" -L`.
o "pQ ) SchoolMember (6 4 W/c4Z .g T"( 6  @ !^
C ID card field 
  g9 C b  !; 8! CH) N<@ . ;"@ 4 P N<@

(6 M   > N<@ . SchoolMember Hg 6Z nF @ FGH9 dg<! Q!
. .P subtypes (6  A subtypes @4 P
" ! SchoolMember L H@9 H<g<! Q! L N !;  U .P!^
i polymorphism UP Q N!G ; . ) !b@ @ G C8 AM kQ9 (6 4
! L d8!6 . Q
 CP(   @    6 HG ! sub-type (@4
N M9 G CP Hg )] Q_ ";  d . <P Hg  U4`9 T
. <G HF  ])(   6 H !  4<] HF (6 T
Teacher HF superclass )) P Hg 59 Q M T"( 6 SchoolMember !G! Hg
8! " q ) . subclasses @6 HF derived classes  HF N!G Student HF
. R 9 (  6 (
Using Inheritance I
Example 11.5. Using Inheritance
#!/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):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
'''Represents a student.'''

SchoolMember.__init__(self, name, age)


self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students

Output
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"

: b!7 0 A `$*
Hg Q (6 Hg) 9 @ H tuple (6 base class ))P Hg ) M9  !  Q)A
self >!)] 9 YZ C9 N@G ))P Hg9 ]__ init__ <)_ d ; Q9 .
A 89 ! ( @<; "5! P . L( 6 ))P Hg ; ! @ ^ C
YZ C9 5L@)9 @<;  o g9 ))P Hg< "constructor" @(  !G
.;G49
; Q9 method   Hg  ) nF @ ))P Hg CL)@( G ! U_ d";
3! Student Teacher A RQ ! U_ A . arguments self >! N!
. SchoolMember Hg A
.SchoolMember Hg9 ] cG@(  )@ 4 9 ] tell <) _ "; d
CQ4 M T"( 6 (  6 methods CL)  @ iMH( 6 H! L 89  ; 54 g
)) P Hg N !! methods @ iMH( 6 H Uh6 method  3 gG"  W .;
. Hg Q (6 tuple (6 M 5 C< ]
i  N!G "L@ i  tuple !L
(6 | 6 8   Y<g`!9 . md

. Q!

.59 UgH! M<g`! @ ]< db6 L Hg< 4<]! 2 3) 9 q
!
3 H 3 (6  G! @ 3 9 > HQ 89 .5 ! L 3 H Hg  L 6 b 5
QH( ! 6 8@ G) Q9 4! T" 56 5 ! L.
89 (6 4<! N   4 !] d.! C Q 4< Q ) (<! 6.
!NG 6 02,
Input/Output
Table of Contents .......................................................................................... M!! L

Files .........................................................................................................................4<!
Using file ........................................................................................................<!)]
Pickle...............................................................................................................................
Pickling and Unpickling unpickling ...............................................................................
Summary ................................................................................................................d.
] )!  G! C@4 N<@ ;3 H 
g@( 6 2W  @
P 8) 
! A .  N RL kQ9 Hg  ]G! d. ". ;  .(]G!; " G4 c
<]  )]b! output C HG9 .(  N<@ print H raw_input )]9 ; nM
string `< G<) N<@ C`M rjust F !; )] 8! CH) N<@ .str (string) class 2)
. C4 !^ help(str)m. M Q right justified H n "

 N<@ .4<! C Q ( input/output !]d.! .o L 
. C`4( " 6 23( " 6 iMH) R H 8 ())  4<! 9
: ,- *
read, 2) )] file Hg< L  nF @ 9 < 4<! )] Y6 ;!
< N 9  N<@ .<! N 9 < !< 2) C9 write readline
!; )@ )< <!( 5  @ .  .<! Y4 TM9 c!
)< "P N<@ 

. <! )] 5 9 89 <H close
Example 12.1. Using files
#!/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

f.close() # close the file


f = file('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line, # Notice comma to avoid automatic newline added by Python
f.close() # close the file

Output
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

b!7 0 A `$*
Y6  ( mode / e! ) !< M nF @file Hg instance/ h9 !
A
(6  ('a') e!'( w') 9< e! ('r') g) !  < e! .59 <!
. 5@ C4; !^ gQ ) help(file) !! P Q

. -<! " close . !<  N 9< file Hg< write  )] )< 9 e!( 6 < Y4 A C( 6 .(Z6A  e!  g! M  . <. !<  p4 Y4 ; Q9
g) N 6Z9 d  g)  g T" . loop/< (6 readline )] )< 9 <! g)

 5 !<
    5 N  56 6 g)  " @   .e] 5
. loop/<M
gG P print H U4b" L<  g) ! print 9 <6 ]G_  A . <! " close . .  g) ( 5 CQ49 <!" 
.YM C9 C!Q R H < poem.txt <!  M N<@ <F q Pickle
(6 Object/ L(  ]^ 6 ]G pickle N@ standard module/Q   6  89
. N<@ L ]^ N!G "  .G  A 5<@ C`M  ( < 6 89
 U A pickle C ! U9   p4 eHb9 C!Q ( cpickle N!G . module/ 
W N<@ modules/  T" !; )] .(8  1000)!9 )C ><9
C ! 3 FGH9  T" C N  M  ". cpickle ]  G  )
pickle

Pickling and Unpickling


Example 12.2. Pickling and Unpickling
#!/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
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist

Output
$ python pickling.py
['apple', 'mango', 'carrot']
b!7 0 A `$*
C ! )] )
` i !C5) .import..as <> 2] G_ d A
> d. (cPickle or pickle) <] C N A  Y Uh6 M T"( 6 N .C!
p C ! T" N  FGH9 M R H 9 (6!  gG eG9
nF @  4!( !< 6 L ]^ 9 e!( 6 file L Y49  A <!( 6 L]^
. pickling N!G <!Q T". pickle C ! dump )@ 
unpicklingN!G <!Q T" . L Q " pickle C <! load )] 9 L 2MG ; Q9
:I *
.pickle C )] ! 4<! 3Q b !] d.! 
 ]<
. exceptions 8)A 54 (6 iMH) (<! 6

!NG \ 6 02,

Exceptions D6 k
  
Errors .............................................................................................................. g.P
Try..Except ...............................................................................................Try 8)A
Handling Exceptions........................................................................... 8)A 3Q
Raise Exception.......................................................................................8)A 6
How to raise exception ................................................................... 8)A 6 4
Try ..Finally..................................................................................................................
Using Finally..........................................................................................Finally )]
Summary............................................................................................................-]<
 H c  M  8! CH) N<@ .;3 9 (6 Q L8) A M  @ 8)A
)]9 RQ AM T" C8 C!Q  3 9 6!`9 c6" c  W <! < 
.8)A
{; 5H } U 6 " 89 A  P T" M` W M `kQ9 ;3 H   
. g.  H]
Errors ?%4*
M_ A Print  H print 9( 6 Ld  g.   .print statement N gG9 m
.syntax error  > g. !  6 89 M T"( 6 .! G M 9
>>> Print 'Hello World'
File "<stdin>", line 1
Print 'Hello World'
^
SyntaxError: invalid syntax
>>> print 'Hello World'
Hello World
_ dsyntaxerror g.P RQ U<Q4 "  .T@ 9 g.  ! "  b 6
error handler.g]" 5
D6 kTry
e>Z .  ]G! d. 
M)Ctrl-d.M  m

>>> s = raw_input('Enter something --> ')


Enter something --> Traceback (most recent call last):
File "<stdin>", line 1, in ?
EOFError
UQ
 !< @    5 N<@ 8Q  U( )) Q " EOFError N@ g.  6 89

(Ctrl-d e>b d. C8!)"


.g.P T" C8 C Q 4 ) (<! 6
Handling Exceptions.. D6 k / A
try-block !Z Q! H) P9 QZ
 . try..except H@ )]9 8)A 3Q !
. except-block (6  ( g.P 3Q C QZ";
Example 13.1. Handling Exceptions
#!/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'

Output
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done

b!7 0 A `$
g.P ! 3Q M  try block <( 6 g. 8 
( statements C b
!L
M  8) g. 3Q U! except H . except < / H(  @ 6 8)A
gQ! 8)A g.P    )! .8)A / g. ( )
9) ZQ! C!3

. try 9 C eH C


P N<@  except 9  23 .8)A g.P ! RQ)

.) Hg R H" 4 
@( G 8H (Z6A RQ! h6 RQ  8) g. 
.C!Q( " 6 CQ49 
@ @ T"4  else H . try..catch <9 eH else H  ; b!
.8)
. " 8)A  6Z<  Q " ! )exception object N<@ ` M! ";
.( 8!( 6 "N<3
Raising Exceptions D6 k" +
 8)A/ g] ) M  b @<; 23 .raise statement )]9 8)A 6!;
UQ6 " !; 8)A g] . exception/8)A 2 N H @ Z  exception object
Hg Error Hg  @ HF H W  H C9 HQ ( class >(  H
.(  N<@ Exception
How To Raise Exceptions
Example 13.2. How to Raise Exceptions
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''

def __init__(self, length, atleast):


Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:

print 'No exception was raised.'

Output
$ 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.

0 A `$
4<) M g. /8)] G ! A 
 W N<@ 9 . 8)A h9 !

< N<@  M ( .ShortInputException d 3 8)A "  .b WP
.R H UQ
  F `
" atleast d.! F length -/ g] L ! h9 @ !> "  db6 error d9 " except H( 6
]d C.( 6 .( )@ 6 arguments parameters C < !HQ ( .8)A
.]G!< H) )@ Hg atleast length: <M object ]G except
Try..Finally
finally )]9 ; !  A  8) 6 " !< )  dW  !< c  
.5 <9! try < p4 finally < 2 N H except  9  !; )] U @<! .block
. !5<( )] 6 2W c .q C.9 ! b gb)
Using Finally
Example 13.3. Using 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:
f.close()
print 'Cleaning up...closed the file'

Output
$ 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

: 0 A `$
CH
  !sleeping FH@ F c<. c ( Q! file-reading C!Q
 g9 
) 89) eH9 C!Q R H   "; 2HG .time.sleep F )]9 g) C@ HF
.R H> /QF! Ctrl-c e>Z C!Q R H Cm @  . (UQHg9
. R H 5 CH
U <]UF (6 R H N< KeyboardInterrupt 8)A_ d
.<! dW  finally H" 4
:#I-
9 . 8) g     . try..finally try..except 9  
 )]
.;" 8)A 6 4
.) 89 H iMH) CH! C`4( 6

!NG " !02,

$ $
 6 7
The Python Standard Library
Table of Contents......................................................................................  
Introduction..............................................................................................................  
The sys module................................................................................................ sys C!
Command Line Arguments .............................................................................................
More sys...................................................................................................... sys @ !^
The os module....................................................................................................os C!
Summary.................................................................................................................-]<
modules/  CL @ N<@  M ( . 8H 2 C )  89 UH :  
 5G9 5< ! C !mQ i ) 89 H N<@ Q ! 9 !P . 4!
.modules/3 H   H! T" Q c@ G9
!3 <  C4 N<@ 8Q !; .H! T"( 6  ]G! modules/  kQ9 iMH)
( nL(  6 " Library Reference/H! "  G
(6 ) 89 H (6 modules  
.;9 ]89 2( 
: The sys module*
CQ49 
 . system-specific functionality m M 4 N<@ " sys" C " ! M
. command-line arguments N<@  M " sys.argv !L

Command Line Arguments


Example 14.1. Using 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
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 : Display this help'''

else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)

Output
$ python cat.py
No action specified.
$ python cat.py --help
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help
$ python cat.py --version
Version 1.2
$ python cat.py --nonsense
Unknown option.
$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

:0 A `$
4<! kQ9  )!M e6 ;<@ .p /p ( ]G @ ! cat  P < M R H"
. output/ ]N 5@Hg9  P` ) 
" sys.argv !L
(6 C
A N<@ ! @` L  <@4 g9 p 8H R 9 C!Q@ 
. 4` Q H 89 i sys.argv[0]   d @ YH`( M R H)
.`Q <( ; . command line arguments
@  !^6Q ]G!< M 5 ] ( ! kQH9 T!! @< Q)A C5) R H CQ3
--  ].3 H M    ]6Q! argument ] G M .R H
d<
(gQ -- help  ]M @  C8!9 .R H@
  HF   ]G version
m !L M ! .R H <] sys.exit ! Q) 4G M .R H 
.C4 !^ help(sys.exit)
C g) C@ HF FGH9  R H N  ! 4<! )! M .  A  @
. P g) N<@ M 2 (6 .q  < <
U! i R H " U9 )   P( 6 ( concatenate !< `. cat  P H)!9
. output/  ]N<@ Q 4<! 8 M<  gH 4< <G<) @ < HF
: sys G =
!G! tuple/ C9  . 5H89 c!
( 89 <  @ Q ;gQ sys.version `< G<G
. ;3 H 89  M  ^C5) F ;gQ sys.version_info

[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.stdin !b sys (C(   )! 6 !P .P Q : * M! 3 H!<*


3 (6 standard error standard output standard input n9g sys.stderr sys.stdout
. (  N<@ ;3 9
The os module "os" 0 
c . ! 5  T" .operating system C> m  @ 4 C8! 3 H   T"
N<@ p  N<@ C!Q ( 9   R H< Y!G U - ;3 H <G `C!@ 
A9 os.sep >! ; )] N<@ <8 P . ; >2<g C"; 
.M m <G |9  G M <!@
.U"9 YZ 5!mQ T  os C ! L6 ^P 8

( ]G! 'posix' "   nt" d8!6 5 ]G ( !` M os.name `< G<G
. p /p
8H cH )U<@ C!Q( " M C C8 (M C!Q C N<@ ` M< os.getcwd() 
.
. (  N<@ |H` @ > M< ]G os.putenv() os.getenv() 
. (M C( 6 <3! 4<! C )! Q os.listdir() 
. 4<!"  M ]G os.listdir() 
. C<  C> ]G os.system() 
. G!( 6 <! ) C ) Q os.path.split() 

>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
< N  NgQ! G!   -M4 ]G os.path.isdir() os.path.isfile() 
NgQ! G!   6Q! ]G os.path.exists()   C8!9 . (  N<@ <3
. CQ49
. ;" help(sys) ]G ! . C4 ) !^ 89 nL( 6 iMH!;
*#I-*
89 nL)( 6 iMH >( @<; H . ) 89 H (6 sys ^< ! L bQ9 

. ;" !^ ! <^ 5   !^N<@ C`M )
.A
! 8 89 (6  CQ3) ( 89 @  2( g> ( ) C`4( 6

!NG QI 02,


6 = 
More Python
Table of Contents.......................................................................................... 
Special Methods............................................................................................ I .$  4
Single Statement Blocks..........................................................................!, g2 0
List Comprehension........................................................................................  
 $ M
Using List Comprehensions ..............................................................D M
@ I
Receiving Tuples and Lists in Function................................   + @
0$  7

Lambda Forms............................................................................................. lambda 
Using Lambda Forms.......................................................................lambda I
exec and eval statements. eval exec g2
The assert statement .................................................................................... assert g!2
The repr function................................................................................................. repr 
Summary..................................................................................................................#I-
(g>) C`4( " 6 5 ]G ( ) 89 @   GL 2 g>9 39 !

q
. A! 8 89 ><9 6Q CQ3 ( 2 3!^

: Special Methods
__del____ init__ 2) C8 classes/Hg( 6 . ! 5 ( ] 2)P kQ9 
.CQ49 5 !
 5 (
<!Q x[key] C!QG 8! CH) N<Q6 . Q ] < )< G ] 2)P  !@
" )< 4 3 ( tuples L(  6 5 ]G ( C8 ) ; class C; 9 ]) 54
!5G4 list HF U<!Q9 89 "   56 ;( 6 4 c . ;<!@ __ getitem__()
2)P C N<@ Q  c .( 3( 6  ] 4! Methods /2)P T" kQ9
. 8H (Q !C( 6  !]Z !L
 ]
Table 15.1. Some Special Methods
!N
@ k
!Q)d 8 ! L Q @  e6 N@G g T"
__init__(self, ...)
L    CH
e6 N@G
__del__(self)
str() ]G @  L printH] G @  N@G
__str__(self)
"&>+" C Q! 3 . 2)  C8!9 "< " Less than N@G
__lt__(self, other)
C Q@ )]
x[key] )54] @!< G  @ N@G __getitem__(self, key)
sequence/<G<G! L len() 3 !!  Q) @ N@G
__len__(self)
:Single Statement Blocks..!, g2 0
 G p4 5 . 9  ( ^H < C )& 56 ;>(  H q
^P mQ! HG9 YM " G .{ 9 C`4( 6 indentation NQ }indentation /<8
p4 N<@ TM |" !;  9 ! ) b A H < c . 
cG 5
.looping statement conditional statement d8 C gG
: Z 9 ; (  8!

>>> flag = True


>>> if flag: print 'Yes'
...
Yes

W N<@ .< CG H p - !C.( 6 ]G   Y `h6 ! ! 
T" short-cut  F ]G A 9 ( ( >; 3 9 CQ3 !; )] " ;
/Y `6Z 89 C5)P ) U GL H)P .& g.P nM  8)9
. <G indentation /<8] G c( 6Z statement
> nF @ H .( 6 @G ; h6 (<@4 e!( 6 89 G4 @ )]U_ A b
... N > ! 5h6 if 4! <! C.  Q9 aboe  (6 .Ld C9 prompts /!

4 e>b g T"59 statement C! @  .Q9 U 5A   statement N
m !  N Q U< H" 4 89 (5 ; Q9 .c<!
 H  enter
. d.!
 
 $ M List Comprehension

 @P! L
;  8! CH) N<@ .M! L!  L
/d])A ]G
. H @   e6  (6 9b
P!  ! L
N<@ C`M
. List comprehensionsk E 06 K$ 6
Using List Comprehensions
Example 15.1. Using List Comprehensions
#!/usr/bin/python
# Filename: list_comprehension.py
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo

Output
$ python list_comprehension.py
[6, 8]

0 A `$*
. (if i > 2) kQ9   @ (2*i) U9 >( H " 2@d M d. ! L
n 
`@ C N <  loops/<M] G ! 8( 6 .Q W ^A <P! L_ A

 8 F ( list comprehensions )]9 nM ( ! p4 !L
@
.  Z  
 + @
0$  7
 Receiving Tuples and Lists in Functions
**  * L9 )]9
 tuple 54 9  parameters/d Q H)A . F 
. ( 6 arguments > " @. @  4  " .(  N<@
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:

...
total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100

args (6 5   ]^N ( ! 6Z arguments ! args >! N<@ * LH 2HG9
 parameters/d Q! N m 23 * A9 c ]) **
 LH c .tuple 54 9
. < key/value !
/4
:Lambda Forms
runtime/C> c
  5@ Q9   L  lambda Y] `G
Using Lambda Forms
Example 15.2. Using Lambda Forms
#!/usr/bin/python
# Filename: lambda.py
def

make_repeater(n):
return lambda s: s * n

twice = make_repeater(2)
print
print

twice('word')
twice(5)

Output
$ python lambda.py
wordword
10

Using Lambda Forms


Example 15.2. Using Lambda Forms
#!/usr/bin/python
# Filename: lambda.py
def

make_repeater(n):
return lambda s: s * n

twice = make_repeater(2)
print
print

twice('word')
twice(5)

Output
$ python lambda.py
wordword
10

: 0 A `$
. 5@ runtime/C> c
( 6   L  make_repeater  )]  
/HQ9 @ H parameter/d Q ". lambda )P( 6 .  <L]  G lambda Y`
. 3  d. 5@  HQ
! "  T"5 G3 YH` " e6  expression
e6 HQ  . lambda form C.] G ! A print Y `N U_ A
The exec and eval statements
`< G<)   ! 8! CH) N<@ .< < ` G<) (6 5 (  ]^89 9 "4 ]G
eG9 8 ". exec H)] 9 H T"" 4 v runtime/C> c
@ 8H ]
: C4)9 T

>>> exec 'print "Hello World"'


Hello World
H eval

:C4)9 8!( 6 < ` ! G<G( 6  ( ]^M` 89 HQ /GM ]G

>>> eval('2*3')
6

The assert statement "assert" g!2


C
P N<@  ; 9 c 8! CH) N<Q6 . true  |"  assert" Y] `G
Y `HQ |" true   g. 6 ; nM< U ]G  c !L
(6 Q
. AssertionError  4" assert" Y `C4 @  .M T"( 6 8 "assert"
The repr function .. "repr" 
C M b N!G )Backticks . L `< G<G (
 C8! N<@ ` M< ]G repr 
.c
 mQ eval(repr(object)) == object ; ) U_ A .UG4 ( CQ4 ()H
A p@

>>> i = []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"

L TQ !6 M !; . Hg< <9


L< C8! N<@ ` M< ]G backticks repr   ))
.;9 ] class ( 6 __repr__ F M d. repr ; <9 ]
: :%*
(6  . 89 Y d C Q9 ve> !;    C`4( " 6 89   !^ !^
R H  H ; 4 U6  P " . ;Hg (6 U ]G   ) mQ gW 
 <! T"
.5L<; H) (6 c
. 89  ) !^4 ) 
} CH! C`4( 6

02, 1 !NG
? What Next A-
  
3 H ) Graphical Software .................................................................................
^ Summary of GUI Tools .......................................................................... GUI
) !^Explore More ................................................................................................
Summary................................................................................................................. d.


c "  Q9  Nq d. UHF  9Q H 9d6 R; 4 cMH
G9 M 8 q .  !9  kQ9H )A R !  !<Q;  nHg!5 (
9 (6 5HG 8 .   ;<@ (>H6 CQ49 ;"9  .CQ4G q '  Q9'.

 @<; 3Q" T!< : 9 ;G4 gG9address-book RP  ])9 -  !;
6Z Q C "  @ iMH5 `A ] ;9 C8
P )P ^ d 5 <Q
@ C8 H ( /
  .5 C4^] 23 5)@ (6 5
.nA c
"  ) C5   N 6 (6!  Q!]< 4( Q  @H  Nq . c
  5 9  4! ;h6  
(b; <!.Y
g$ -
) (>H  A
 ;(.
*   <Q C8! class ].-
*)]  ]^ L ] -)!H@9 U4 T.key/
*)] ! ^] cPickle C L !)9 @< N `<.2
*)] 2)P! < 3  6Z" Q CP].
@  
 @< N  CQ4 C; !; @( ; 9 R H 8 .q @< N 4 )9 ( C 
"5   . mQ" T] g . ( ; .59
; kQ9g ! < <; 9 8 :
$/!7 ! Graphical Software $
H }GUI 5!]G ) ])9 {Graphical User Interface- 9 8 --M9 c 5
9 C!Q ;3)  ])9 9 8 .!;  irfanview kuickshow] ;9 ( C8
; !Q)9 H 9 (6 GUI 8 4<WP] .59 4<WP( (  ; Y!G9 (6 9 9 R 8
)] !H ( ! c  (6 59 C ><9 5 C++ W <>.
D   !$6 $I GUI  I 6 :
.PyQt" T( >< 9 8 ` Qt" )P " <5) Qt .KDE U<@ c9
!Q)A <>
   `.m !`! Qt 5L!"< .!; )] `9 5
3 / @< p N ) 6 gb! 5  c )] N<@ 5PyQt .
3 /  9 /p N<@ (GPL) `. HF R  p 6! C9 

'GUI Programming with Python: Qt PyQt  3 !` .<  3 9


.C4 !^ official homepage !) M4` m Edition'
U<@ c9 ) "P " GTK+ ` 89 <> ( T" . PyGTK
.GNOME
Hg !;  5Q  YH`  3!9 ; !Q)A( 6 W !8 5 GTK+
N<@ C!Q GTK+ GM9 ] nL  .U@ NW A   )  5!`!  9 !.Q )GUI
N<@  !!< 3 H "; M 3 H !; ` .Q9 C!   N   p
.C4 <!^ official homepage !) M4` m . GTK+
.wxWidgets ` 89 <> T" . wxPython
 p N<@ C!Q  portable / !M (56 ; W 59 . (!<Q NM 5 wxPython
 g| 9 } IDEs Q  . embedded platforms 3 ! C!Q ` N<@ N 
( Stani's Python Editor) SPE C8 GUI `!!N 6Z9 wxPython ! <{  
. wxPython N<@  !!< 3 H "; M 3 H !; ` . wxGlade 5 `! 
. C4 <!^ official homepage !) M4` m
c ; 9d6 IDLE c ]) ; nH) . (  6 P n 
 T" TkInter
. <  PythonWare.org " F-G TkInter 9 ] nL  . C!Q  TkInter
 P .  ) N<@  p /p C N<@ C!Q portable/ !M TkInter
. $ $
 6 A =  TkInter
GuiProgramming wiki page at Python.org : m <!^ ]
GUI  G #I-
P
 @<; ]  <; . 89 N<@ GUI 
)  A U_ M G
 6 !; C :  . M (6 P C Q . c; 4
N<@ !Q; Td@!"
. ! d  p  5<@ C!Q; 3 H  !` : (8 C Q . GUI
. GNOME KDE p N<@ 5 ]G  ) 5  : i8 C Q
:$-7
1  2,
 .  C!M! . ) 5  3 9 @ " 5 <`6 C`6 9( 6 6 
N! bA !; Z !  " m 5  .P ] ` wxPython
5<!@ ! ( GM    H i byte-of-python mailing list : H! L
.  5
: =  N
U4 9 U "  .U@ iMH  H! T"( 6 3) c
 mQ (6 .<  H 8H ) H!
9 (6 Q9! CH
8H ) nL  d. 3 9 9 N  . 89 (6 '6Z gH '4G<6
. 89 ><9 H R 9 9
G4 89 >   3) . 8H !) GL M4` ( T" Python.org
. 89 2  ]< g !
 3 i H L ]<  b  .><
;! .>< T"   3 i H N<@ H.P! @ 3 ( Comp.lang.python
cA N<@ ! @3! T" N !;   .;< H.P! @ 3 N; G4)<; L))
Q 3 ( ( mailing list H! L N! bA Google Groups )]9
.H.P! @ 3!
C 4  YL` 4 ! @ 3 ! i 
 <>2 : Python Cookbook
. 8H ]G C U
9 A " . 89 )]9 C !kQ9
. David Mertz. 5H . 89 @ 
! <>A <G<) : Charming Python


 !  " . 89 (3 H H]    " : Dive Into Python
Q9 ' 89 (6 '> Dive Into Python    W ;  ) q c6 (M
XML ^53  d <9( ; >  ^ 6 !9 Z! @ ! 3 C! .;
.Functional Programming Unit Testing Processing
)]89 (6 R 9 9 !; U( Q " .6( > 6 89 G4 Hg  : Jython
9 9 ;M`  ;" 6 R H c .RZ G R 9 Jython !;" 6 H
.; M jython (gQ
NET / Mono / ` N<@ U<> ! .C# ><( 6 89 G4! nHg : IronPython
( .P H! NET H . )]89 (6 R 9 9 !; U( Q " .DotGNU
e6 Y<` pre-alpha <!9 3 9  ^Iron python . ;" d8 !` T" 6 
.q N 23<
C C!Q ) c6 )  N b
 ironPython 2 " Jim Hugunin
. CHG!( 6 ironPython <   N C 
bytecode N H  Lisp  59 ( . 89 >< Lisp frontend 5 :Lython
.Q! 89 < . C!Q  ) 5( Q  " P 89
"Daily Python-URL!
!5! P . 89 (6  ! Q Q 
, Vaults of Parnassus T" "; 89  .o N<@ M  L dF N<@ ;<Q3
. 8 8 Python Notes, dirtSimple.org, ONLamp.com Python DevCenter
::I
HQ c
 8 q c ." !5 9 ( !   ""  "  5 N q <
{!(  }6 H !; . 89 )]9 C !Q CM QG ; d9 c 8H !5]  G
;9 . Q   2 5<] ! A ( Z!( 6 c ( P C9  <5
. ! H( 6  ".8 8
****

      


...    
  
!  "
5"6 ," 4& 23.  1 ,-. + 
*) (%&  $  
 2.45 , - 2008 BC. + 17 @&$ - 1429.9: 2" +11
....N 4)$9 
2L C    K" 4& $1C ." 2"!  J
http://www.linuxac.org4.  51 " 2 P %  ( O9
c"e .d cN + ,a $ + )$. * .. 1 43a 4)$9 + -.
[kaspersky0] i9 4 .h:

. - ,C 1Jp

You might also like