Professional Documents
Culture Documents
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
**
98 ( <; <> << ( ! 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<; .3H
**
" 98!9 >< (!<Q C9 3H8 .( 5G )) ! . LH( 4 <! 3H
]H "; 5 ; @! U @ U6Q ;<@ C^5 ! H _4 4!<4
` !; 9 <Q8 " ; H. @ HG 3H!; b <Q
98 "
H. 2 c G6 3H9 HG 9 !5 Ud.A 9 98 > 3H! <b4;
cb @< N 8" T6d.A .
@< N W; ( 9 eG9 UH8 @!
) 2 ` > YH 3H! <b4; !!
** !!
(6 9 P 98 @ c39 NH cH8 R" (3 ) cQg CQd5) cH8
@<( .A 9 98 9 .Qt H 4<W
!@h9 c (6 iMH H8@ N c N<@ 6`9 ; ! ; 5 !C3H
!5 < @ 56 9 cMH8 ( > 3H! HHM.U
"; c4 PyQt 4<W !9
;" Perl-Qt 98 ( <> ] (9
Q9 9 @ iMH 9 > (68 .( !!5
kQ9 2 O'Reilly
5 c 9 m>< !8 UH N H
5 .
(9 c53 N nL( 98 ; `] c >
@6 (g
( i 5Q CQ H. 3H9 HG9 @ W 58 <! 5W
LH!< !Ld
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 (68 C "
G! ( !3! M!` !4
" 9 !md ]` @ 98 ( c (6 U6 m p4
- c W( U6 c"9
8 - 53 @ AH
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 <Q8 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@ Z9 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 iZ9 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................................................................................................................
!^ 98Features of Python ............................................................................................
<]Summary ..................................................................................................................-
! 9 p Why not Perl? ...............................................................................................
!3HWhat Programmers Say ..............................................................................
* 98 ( <; <> << ( ! A@ gG9 5
@<) N) . G
4| (6 ( ) <5^ C (6!< !9 2)) > 5<@ C!Q 39
! 67 $ :
98 ( > <5) 3H
<Q .M 49 @ !G N<@ gG9 CH
C!Q Q6 5 3H. L
@ 98 56 9 H NG4 QHF 29 CQ3 8 > 3H 8
9G )@ g (6 nHgQ !A3 @< mQ N!` .
)
} mQ" T!G ^!9 (6 C`4 G(.
::9
W" Guido van Rossum 6 ) > 98 5<@ n<F; Q9 )A|5 Z@ U
@ Hg )" )9 ( < 9Q8Lg"" "Monty Python's Flying Circus
C8 59Q8
( CM >" @<F @ 5 4` nG 4A9 5). 5M
=$ < 6:
**:?$1
98 > Q9P gG9M .
9 R H8
UH <> <^ @< N W5
^<3 !
QHF" )A!QG H8 @ m)
.5 U ; Y^ @< C N!< 8
<> . 5G4
** * -:@-A
! )9 8 )>< <5 H <Q (6 599 .3H8 M <5) 2@ ! ) nH. T
**! , 2:
98 ( 8 !` (Free/Libr and Open Source Soft-ware) FLOSS Y<gH RM !4
!`.
HQ9 gG9!; M9 &G" T3H
4 !` kQH9> @<5
)] ^ 39 (6 5 Q c U!; CQ4" TP.
54 `H N<@ FLOSS Y<g ! !3" (6!.6Q
" )H 98 P -
U d. !G C9 5GM ! !3"
e6 98 .Cb6
.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
.3H
userlinux. opensource.org G)! : Bruce Perens
G6! 89 Z
. Q QL9 @ p )
Q C!Q Userlinux
.Userlinux CH
@ ( )GL 3H > 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) R9 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 R9
C8 2 ..P 3H
: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 RH < C!M d. ;" 5G9 89 cH8 m HG9
.;
m N<@ 89 c
H`; 9
4) `@ 6
.89 N<@ P 39 2
) C`4
\6 02,
F4? I
:
! < `Q) - `M . - interpreter prompt G4! /iM !Q) - !
d] - @G N<@ `M - Executable "4< <9 89 R9 - C
!Q - output ]:
*
C> _4M 2
<!; " Q) .89 (6 'Hello World' <RH C>
q)
.89 R
9
-:;
39 C> 89 )]
F
( G R9 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! RH 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 RH<]
.ENTER 4!9 @H Ctrl+z (4 e>Z 9 P g) ( 6, .BSD/LINUX
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 R9
. 8
^P C
iM9 ( 2 <9 )syntax highlighting ()) P
H<g!
.U<!@ 4; `
39 ; NG N 89 (6 colorized <R
H< 4<]!
8 syntax highlighting C!Q9 IDLE i .IDLE !Q) @<;
C
!QG c
..! Z IDLE !Z ;
39 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. 3H c . M! 9 ]8<; 6 tg]d Linux / FreeBSD C
!QG c
4G)
P M!! 59 <A .Emacs VIM C!QG ;! ! 6
.89 N<@ ;39 9 !5!Q)
( KATE C
!QG |" !; LH 3H c .(39 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 R9
.5) 8 89 R9 9 C
Q3 56 - M . .
2` - I
U<> UH R9 39 > <Q ;<H) (6 c <! U < .3H N Q @ q
Simon !
.U<> @ 'Hello World' : U<Q6 ;<@ C -- 'Hello World' R9
. 'Cb6 C9 ><< Q N<@ ;@G! 3H 9P ^ <Q 98!9 5 " :Cozens
helloworld.py :)9 Um4 ( RH 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 @ RH " 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 ; R9 C> (6 cM3 -- !5 ; Td@ H ! R N<@ c<`
!<@ .. RH C> Td@ H ! eHb9 !"RH 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
:0A `$*
( --" comments - <Q ": <!T" N!G .RH g) ( 6 m@
. RH " 4 ) P( 6 n<Q # ^ ! N<@
@ shebang line N!G ( . P gG . 8)9 <Q] G A 89
RH " p\p H] " h6 RH) 9 @H # # @ H@ !< !`6
.RH" 4 @ interpreter G4! " C!Q 23
platform ` N<@ RH C> !L; h9 U @<! .( G( 6 C`49 ) "
. python helloworld.py :P C8 P g) N<@ H interpreter G4! M d.
@*
4 " -- RH( 6 !5! C4 kQ9 ; 39 (6 (d@ < Q)]
) Q9 ;G4 c ! -] " ".RH U9 56 5G9 ! iM9 ;39
!!5
( print !< .'Hello World' :-@ " Hg9 e6 -- Python statement (< (< Q
!! n< A --string `< G<) H@9 5' Hello World' CQ 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 `RH g@ @< Q A .RH A
. !`RH C> Chmod
$ chmod a+x helloworld.py
$ ./helloworld.py
Hello World
" !02,
$ 4
Literal Constants ..............................................................................................6M c98
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
!>c98)] 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 c98 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
strings $2D 0 :1
. !@ <!3 3 )) ( .M< G<) ( : strings
;<@ ;" 5H ( 89 R9 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<@
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?'. :* ( $%& "!
Variables !$<
F N M9 M -- d
! Q )YH` ! e6 literal constants 6M c98 )]
eHb9 !>.( `6 !>5m i ".b 5 ( 6 2@d< Q! ]^
cG !>.Variable > )]9 !; ]^ (5!
4 ! UP - 5!) N<@
literal 6M c98 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<@ RH( 6 ]G (N 89 "
( object L ) U@ ( something - " (U@ AH6
Object Oriented Programming users :* $D /!7 I1 9:**
@P ) object
Variables literal constants 6M c98] !> G q) Save the following
. RH C>( < 6 ( 8!_ 4
How to write Python programs :6 + b!7 .` $
: ( M N<@ 89 R9 C>_ 4M
) `@6 q
Output
$ python var.py
5
6
This is a multi-line string.
This is the second line.
How It Works b!7 0G $,$
P !> N U!
(i) literal constant (6 c9) h9 !
A .RH " C!Q;
U9 >( H | Q H 5P statement Y `N!G gG " .(=) operator CQ!)] 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
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`}
2 9 H] i 89 U g] .(8 gG 9 (6 W6 6G !_ A
; " NQ .YM` U N<@ W RH C8 .MM W RH( " 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 0A`
$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 ( .!`
QI 02,
!$7A 0A
Operators and Expressions
Introduction ............................................................................................................
Operators ...............................................................................................................CQ
Operator Precedence .......................................................................................CQ 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/dQ! N!G H kQ9 2<g : Operators
operands
. 5 )]operators :CQ ]` 39 ) Operators
8! CH) N<@ . H interpreter G4!)] 9 <8P( 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 CQ 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
Right
Shift
<
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.
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 CQ H)9 9 gQ ( 3
.(^
N<@P CQ CH
3( 6 NP CQ
! 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`
CQ< H)P M operators and operands dQ!/M CQ! 3 ( )
P)]
8 C9 M 2 + (3 * 4) 8! CH) N<@ .(
6 C5); 39 CQ3 Z9
Z
L>( H A dQ9 GM9 ]G 23
) ( P .; Q9 (C " . 2 + 3 * 4
.( (4+3)+2 C8) .M@
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
Output : bD
$ python expression.py
Area is 10
Perimeter is 14
: 0A `$
>!( 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 RH YH` g m R N<@ `M C "; 5Qb 89
RH!< HG9 <5) M CQ3 89 ( 4 N<@ 8 ( "R( 6 6G! n<9 Q) |"
. !!
'Area is'
::I
expressions HQ operands dQ!/9GM M operators CQ )] 4 c
.R9 Blocks C N<@ ))( H (
.H/ Y)] `9 39 (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 ( RH( 6
kQ9 ]RH 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:
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
: 0A `$*
>! ) M . " Q " 6Q] G!" ]! . 6 RH( " 6
)] 9 ]G!" ]! . .23 T YM @N" number"
raw_input ().
.( C`4( 6 5@ !^ 9 ).5 ! @ )]RH ^ 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 - CM
RH 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) RH 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 RH" 4 ( GL < M T"( 6 . if H < M ( H N
. FGH N5!9 U5 v RH 5 89 Q9 . print 'Done' H
( "6 N 5md ( @<; A 8 N c5H eG9 RH " W
39 4<]9 |; P HG9 4 C9 gG9 ) gG9 !< 5< T" .eGH RH
)5Q YH` ) ; Q9 H T" C YH` ; 2<g ( C/C++ >
. ; 6 59
3H + + / 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 0A `$*
U!]9 4A9 U Y!G] G! !^ guessing !] HQ 2Q< RH( " 6
- 9) (6 <Q6 ! - !] C @ RH" 4 N cG MM U!] A
: " while " H )] Z9 " .
>!< 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 CG6 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"
Output
$ python for.py
1
2
3
4
The for loop is over
"
: b!7 0G $,$** *
<.)] 9 @P< G<G >< . @P< G<) @Hg9 !
RH( " 6
"range
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 0G $,$*
. C( 6 <.! length QHF ] G! d.!" .9 !
RH( " 6
"quit " ] G! C.! -M6 d. RH
. F 69 !
. "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!
: b!7 0G $,$*
])" . C
P N<@ 3 @ e6 T"4 ]G! C.!< H
RH( " 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 ! @ )]RH ( ^ :
M. )@ N!G! 9 Q" . @ ! RH( 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 0A `$*
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 0A `$
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 0A `$*
. 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 ; ! . RH
.( < ]6 Q >! Z9 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 0A `$*
!
G @ 6 global (!@ > x 9 d@ ]G global statement
Output
$ python func_default.py
Hello
WorldWorldWorldWorldWorld
: b!7 0A `$*
Z6 !
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 0A `$*
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
Output
$ python func_return.py
3
: b!7 0A `$*
({ 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
Output
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
6 02,
Modules
*
@ )] @ . Q nF @ ;39 (6 !; @ )] c
M) < A( 6 : module !.modules !3 c!.
! ! Q 5H ( .A RH( 6
module ) < 23 . R9 (6 @ )] " !.54Q9 c!
(! !>
. Py .9
) 89 H ]G ( ! g ( T" .U4 4)d .o R9 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 0A `$*
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 ;" . ;39 (6 ]G .o "argv" > UH A )A)< P !^ "
. sys C) ^ !A ; N<@ Z9
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 ;39 N!!
]G c IDE g) M F @ iM9; 39 C> 9 arguments. L d. ;3H
C>9 !
6 using_ sys.py we are arguments N!G! 89 R9 "4 @
N ! arguments @ H@ U Q9 .P P python P sys.spy C!
. sys.argv >!( 6 5]^9 89 . RH
;" . sys.argv !L
(6 argument ! L C!Q{ > " c9G }RH " )
' 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 RH 89
<!Q^ 3 i @) 8 ) -<] R9 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) ;39 N" argv" !$<! $ (! 7
!; )]sys C( !6 ]G!)! P C ) ." from sys import argv" H@
H@ )]23 @U9 . ^< !C C!Q " . "from sys import *"
H@
(6 5) 8 g T"59 )RH 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__*
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 0A `$*
!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 0G*
. ;" C HQ 8H R9 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
Output
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
: b!7 0A `$*
p4] G_ Adotted notation @ )]89 3 . C @ !N{< g! 59 !<})
p4notation . P
` F <Q Cm @< p " 5<W ^! "(89"Q 4Z
from..import*:
: 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()
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" . U9class 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
b!7 0A `$
>!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
# 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 0A `$*
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@
Output
$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?
b!7 0A `$*
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 C4! Q) 23 U ! .P nM
N C!Q " .;<
( H9 Q 8H .%s !; )] c
mQ
G b " i UMM` 4 !g@( 6 2W
; .
P
. ;39 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!)/
'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 0A `$*
4! M d. key/value >< . U
nH) )]
"9 ab ` 9 !
: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
b!7 0A `$*
<!@ U N<@ U b " .<G<G! 6 @ N<@ `M< 54 )] 4 A
C9! H 89 ; 2<3 ) Td@ H ] [ ! 6Q 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
#!/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 0A `$*
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 0A `$*
` 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
R9 9 ) )) @ T" H C .C`49 89 (6 3! H C) 9 !
Q 3M9.
Q( 6 R9 9 `! 4! <( 6 ) ( 6 89 ))8 A
8H (M.
!(A 02,
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 39 H] i H.A( < 6 q M
. RH( g.A )bugs 39 YM` < N A @< G6
b!7 0A `$*
time os ^< !4G M. Tg]6 g. N `! CM9 !
_ 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!
.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
. 3H < C> < N!G " .( 6 c
( 6 (FA& G R9
8! CH) N<@ .
c ! ! C!Q A NA RH )@( YM C9 Td@ RH C!Q
& U9( 6 g.
c YM C9 RH `! c C
. ;39 YM` gb) < `! N Q @<; Q) 2) C9
: $6 r*
N<@ C!Q U! N U<@ GM kQ9 . ! ; . C!Q cHG NA U]G
. 3H < 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:
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 0A `$*
C C.( M) 9 C nM > ( .UG4 RH " 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 39 CQ3) H C9
: 66 r*
8 @ FA& G 8 C!Q9 c!
c @ C!Q 8] G
CH) N<@ ! C c F] G C W 9 n4( 6 9Q UFA& G
>T" Z @ @ 8! RH< 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.
Output
$ python backup_ver3.py
File "backup_ver3.py", line 25
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax
b!7 0A @ `$
89
" m( Z A c9G( Q > ! g. ! 89 .!C!Q A RH"
eHb H N .T@ g] @ ! " H] "; 89 U
( g]_ d @ .T
. gG ; 39
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 " .3H 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 0A `$*
<Q 2@G .3 U]G( 6 5<!Q9 !
(< Q4 GM d. (b!! @ q C!Q RH"
d.! F YZG | 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` ;39 CQ3 v ]M ;! i RH< 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
.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 .3H 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 ( RH 9 59 N! g
! C!Q U < RH )] . YM` H.A . RH< gG9 > "49 9 .!`
Do It-Test-" ")]--CQ6 ": T"( 6 !) ^ Z q .
! NH A ! ^3H " .<g! M N<@ @ !P "Use
" Software is grown, not built "
:I
T" C8 9( 6 ( 4<]! C !89 (6 ] 9G/RH C!@ 4
YH` ; NG N C`4( " 6 <Q6 !<8 ;G49 ;39 4! U 3 !9 .RH
" object-oriented" L 3H! <()
} 6. C !C N<@ @ db6 89
!NG 02,
* $D /!7
Object-Oriented Programming
Introduction ............................................................................................................
Output
$ python method.py
Hello, how are you?
: b!7 0A `$*
Output
$ python class_init.py
Hello, my name is Swaroop
: b!7 0A `$*
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 .
__init__
F
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.
: b!7 0A `$*
Hg N !( population L Hg > QHF H (6 @G U CF 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 RH( " 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< 8P( 6 T<!Q) " del H
]G e6 ;<@ Z9 ; C!@ . C!Q) g T"! Z p ]G W L @ C!Q __del__
(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
. R9 ( 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.'''
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 0A `$*
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<]! 23) 9 q
!
3H 3 (6 G! @ 39 > HQ 89 .5 !L 3H Hg L6 b 5
QH( ! 6 8@ G) Q9 4! T" 56 5 !L.
89 (6 4<! N 4 !] d.! CQ 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<@ ;3H
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<! CQ ( input/output !]d.! .o L
. C`4( " 6 23( " 6 iMH) RH 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
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 0A `$*
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 RH < 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
Output
$ python pickling.py
['apple', 'mango', 'carrot']
b!7 0A `$*
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 RH 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<@ .;39 (6 Q L8) A M @ 8)A
)]9 RQ AM T" C8 C!Q 39 6!`9 c6" c W <!<
.8)A
{; 5H} U 6 " 89 A P T" M` W M `kQ9 ;3H
. 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
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 0A `$
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
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.
0A `$
4<) M g. /8)] G ! A
W N<@ 9 . 8)A h9 !
< N<@ M ( .ShortInputException d 3 8)A " .b WP
.RH 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
: 0A `$
CH
!sleeping FH@ F c<. c ( Q! file-reading C!Q
g9
) 89) eH9 C!Q RH "; 2HG .time.sleep F )]9 g) C@ HF
.RH> /QF! Ctrl-c e>Z C!Q RH Cm @ . (UQHg9
. RH 5 CH
U <]UF (6 RH 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
$ $
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/3H 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
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!
:0A `$
4<! kQ9 )!M e6 ;<@ .p /p (]G @ !cat P < M RH"
. output/ ]N 5@Hg9 P` )
" sys.argv !L
(6 C
A N<@ ! @` L <@4 g9 p 8H R9 C!Q@
. 4` Q H 89 i sys.argv[0] d@ YH`( M RH)
.`Q <( ; . command line arguments
@ !^6Q ]G!< M 5 ] ( ! kQH9 T!! @< Q)A C5) RH CQ3
-- ].3H M ]6Q! argument ] G M .RH
d<
(gQ -- help ]M @ C8!9 .RH@
HF ]G version
m !L M ! .RH <] sys.exit ! Q) 4G M .RH
.C4 !^ help(sys.exit)
C g) C@ HF FGH9 RH N ! 4<! )! M . A @
.P g) N<@ M 2 (6 .q < <
U! i RH " 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
. ;3H 89 M ^C5) F ;gQ sys.version_info
(]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
: 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)
"&>+" CQ! 3 . 2) C8!9 "< " Less than N@G
__lt__(self, other)
CQ@ )]
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
: Z9 ; ( 8!
W N<@ .< CG H p - !C.( 6 ]G Y `h6 ! !
T" short-cut F ]G A 9 ( ( >; 39 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]
0A `$*
. (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 549 parameters/dQ 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/dQ! N m 23 * A9 c]) **
LH c .tuple 549
. <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
make_repeater(n):
return lambda s: s * n
twice = make_repeater(2)
print
print
twice('word')
twice(5)
Output
$ python lambda.py
wordword
10
: 0A `$
. 5@ runtime/C> c
( 6 L make_repeater )]
/HQ9 @H parameter/dQ ". 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
:C4)9 8!( 6 < ` ! G<G( 6 ( ]^M` 89 HQ /GM ]G
>>> eval('2*3')
6
>>> i = []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"
02,1 !NG
? What Next A-
3H )Graphical Software .................................................................................
^ Summary of GUI Tools .......................................................................... GUI
) !^Explore More ................................................................................................
Summary................................................................................................................. d.
c " Q9 Nq d. UHF 9Q H 9d6 R; 4 cMH
G9 M8 q . !9 kQ9H)A R ! !<Q; nHg!5 (
9 (6 5HG8 . ;<@ (>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 RH8 .q @< N4 )9 ( C
"5 . mQ" T]g . ( ; .59
; kQ9g !< <; 98 :
$/!7 ! Graphical Software $
H }GUI 5!]G )])9 {Graphical User Interface- 98 --M9 c 5
9 C!Q ;3) ])9 98 .!; irfanview kuickshow] ;9 ( C8
; !Q)9 H 9 (6 GUI8 4<WP] .59 4<WP( ( ; Y!G9 (6 99 R8
)] !H ( ! c (6 59 C ><9 5 C++ W <>.
D !$6$I GUI I 6 :
.PyQt" T( >< 98 ` 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
! " .89 (3H 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 R9 9 !; U( Q " .6( > 6 89 G4 Hg : Jython
9 9 ;M` ;" 6 RH c .RZ G R9 Jython !;" 6 H
.; M jython (gQ
NET / Mono / ` N<@ U<> ! .C# ><( 6 89 G4! nHg : IronPython
( .P H! NET H . )]89 (6 R9 9 !; U( Q " .DotGNU
e6 Y<` pre-alpha <!9 39 ^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
****