You are on page 1of 373

:2010 12 20 2:58:11

: pahkey


1990 .
Monty Python's Flying Circus
. (Python) (Parnassus)
, .
.

, (Google)
(Infoseek) ,
.
.
,
.

wikidocs.net PDF, page : 1




00.
01.
1) Endless-Edition
2)
3)
02. ?
1)
2) ?
3)
4)
03.
1)
[1] (Number)
[2] (String)
[3] (List)
[4] (tuple)
[5] (Dictionary)
[6]
[7]
2)
[1] if
[2] while
[3] for
04.
1)
2)
3)
05.
1)
2)
3)
4)
[1]
[2]
06. ?
[01] ?
[02]
[03] tab 4 space
[04] 12345 12,345
[05]
[06] ?
07.
[1] ?
[2] PyUnit

1
2
4
6
8
9
10
12
13
16
18
20
25
26
27
31
50
63
66
74
76
81
82
92
97
102
103
117
121
130
131
163
172
177
178
198
215
216
219
220
221
224
226
228
229
232

wikidocs.net PDF, page : 2

[3] SubDate
[4]
08.
[1]
[2] django
01)
02) (Templates)
03) (Models)
04) (Forms)
05) (Sessions)
06)
09. Tips
[01] API
[02]
[03]
[04] SMS
10. Quiz
[01]
[02]
[03] PrimaryArithmetic
[04] Spiral Array
[05] Four Boxes
[06] Slurpy
[07] Eight Queen
[08] Tug Of War
[09] LCD Display
90.
01. 3.0
99.

234
244
254
255
261
262
266
271
281
285
288
289
290
295
298
301
304
305
307
309
312
316
323
330
334
343
348
356
372

wikidocs.net PDF, page : 3

00.

2001 []
:

" "" "

** () **

[2010.12.23] PDF .
2010 . ^^
2010.12.22 " " PDF .
B5 .
PDF

[2010.12.21] django .
" " .
http://wikidocs.net/read/1511

[2010.05.10] .
" " .
" " .

[2009.07.22] .
.
( .)

wikidocs.net PDF, page : 4

.
.
. ^^

:pahkey@gmail.com

[2009.02] Endless Edition .

" ."

wikidocs.net PDF, page : 5

01.
(http://wikidocs.net) .
(F2) .

?

.
,
.
.
,
.

< >
1.
.

2. ?
,
.

3.
.

4.
.

5.
,
.

wikidocs.net PDF, page : 6

6. ?

.

7.
Simple TDD ,
.

8.
,
(django) .

9. Tips
Tip .

10. Quiz
Quiz .

90.

.

wikidocs.net PDF, page : 7

1) Endless-Edition
Endless Edition .
.
. "
"
. . (
.)

" "

Endless Edition .

""

2009.02

wikidocs.net PDF, page : 8

2)
'>>>' .
.
.
.
. .

.
.
,
.

,
.
.
.
,
.

.
.

2001. 06

wikidocs.net PDF, page : 9

3)
CTO
yong@linuxkorea.co.kr

. ,
' ' .
,
. ? ,

.
.
,
''
. C++ ? (Java) ?
C ?
( C++ C++ .
.) .
.
?
1999 (Python) .

.
.
( )
''
.
( 100%
.)
.
. 2000
, ,

.
(Style).
.
(fun) .
.

wikidocs.net PDF, page : 10

( C# ).
.
. C++
C++ .
.
'' . 1~2
. ,
Guido van Rossum
,
(
) .
, .
.
.
(fun) . (
) .
.
,
.
.
.
.
.
.
(fun)
. . "
. , ."

. .
Na .
.

2001 7
Happy Python!

wikidocs.net PDF, page : 11

02. ?
1990 .
Monty Python's Flying Circus
. (Python) (Parnassus)
, .
.

,
(Google) (Infoseek) ,
.

.
,
.
,
.

wikidocs.net PDF, page : 12

1)
. .
.
. .
,
.


.

.
.
. .

if4in[1,2,3,4]:print"4."

4 1,2,3,4 "4 ." .

?
.


?
, . ,
?
.

, ,
, 1
.

. ,
, .
.

wikidocs.net PDF, page : 13


. C . , C
. (
?) C
. C .

. ,
.
.

. (Guido) .
.
.
.

#simple.py
languages=['python','perl','c','java']
forlanginlanguages:
iflangin['python','perl']:
print"%6sneedinterpreter"%lang
eliflangin['c','java']:
print"%6sneedcompiler"%lang
else:
print"shouldnotreachhere"

.
. .
({, }) . ,
. .
. .
.


.
.
. , ?
?
. ! ^^

wikidocs.net PDF, page : 14

Life is too short, You need python.

.
.

wikidocs.net PDF, page : 15

2) ?
? ?
.
.
.
.
. .
.
.


.
. .

1.
(, )
.

.

2. GUI(Graphic User Interface)


GUI .
GUI .
Tkinter . Tkinter
GUI . Tkinter 5
. wxPython, PyQT, PyGTK Tkinter
.

3. C/C++
(glue) . .
C , C
.
C . ChartDirector
C .
Legacy()
.

wikidocs.net PDF, page : 16

4. CGI
WWW .
.
CGI . CGI
(, ) . CGI Common Gateway
Interface . CGI
.

5.
. C
. Numeric Python
. Numeric Python C .
.

6.
Sybase, Infomix, , MySQL, Postgresql
. MySQL .
.
pickle .
. pickle .


,
. ,
.

wikidocs.net PDF, page : 17

3)
. .
.


. http://www.python.org ( )
. 95, 98, NT, 2000, ME
. exe
msi. .
, .

.

PATH="%PATH%;C:\Python27"

Python27
.

$python-V

. 2.7
2.7 . http://www.python.org Python-2.7.tgz .
.
.

$tarxvzfPython-2.7.tgz

$cdPython-2.7

wikidocs.net PDF, page : 18


Makefile configure .

$./configure

$make

$su
#makeinstall

wikidocs.net PDF, page : 19

4)
, .

.
" , " .
.


.
[] [] -> [Python 2.X] -> [Python (Command Line)] .
.

Python2.7(r27:82525,Jul42010,09:01:59)[MSCv.150032bit(Intel)]onwin32
Type"help","copyright","credits"or"license"formoreinformation.
>>>


. Ctrl-Z
( Ctrl + D).
sys .

>>>importsys
>>>sys.exit()

2
.

.
1 2 3 .

>>>1+2
3

wikidocs.net PDF, page : 20

>>>3/2.4
1.25
>>>3*9
27
>>>

a 1 b 2 a b 3 .

>>>a=1
>>>b=2
>>>a+b
3

a "Python" print a a .

>>>a="Python"
>>>printa
Python

>>>a=2+3j
>>>b=3
>>>a*b
(6+9j)

a 2+3j . 2+3j .
i 2 + 3i j .
2 + 3j 3 . 6+9j .

if .

>>>a=3
>>>ifa>1:
...print"a>1"

wikidocs.net PDF, page : 21

...
a>1

"..." .
for [1, 2, 3] .

>>>forain[1,2,3]:
...printa
...
1
2
3

([]) . "[1, 2, 3]
a print a . a 1,
2, 3 print a .

while .

>>>i=0
>>>whilei<3:
...i=i+1
...printi
...
1
2
3

while ~ . "i 3 " "i = i +


1" "print i" .i = i + 1 i 1 . i 3
while .

>>>defsum(a,b):
...returna+b
...
>>>printsum(3,4)
7

wikidocs.net PDF, page : 22

def . sum
. sum(a, b) a, b a+b .
3, 4 3+4 7 .
.



.
.
.
.
.

#hello.py
print"Helloworld"

"hello.py" . "#
hello.py" . '#' '#'
.
.
py .
py . hello.py
hello.py .
( hello.py C:\Python .)

C:\WINDOWS>cd\Python
C:\Python>pythonhello.py
Helloworld

.
PATH , hello.py
. ( -
.)
"Hello world"
.
.
.
.

wikidocs.net PDF, page : 23


by 2010.01.11

( 9.10 .
.)
'' . ,
python,

Python2.6.4(r264:75706,Dec72009,18:45:15)[GCC4.4.1]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>

.
py , "python .py" .
home, home .
"" . ,
/home/( )//hello.py . ABC
'' 'simple calculator.py' , python
/home/ABC//"simple calculator.py" . ( .
UNIX Linux .)

wikidocs.net PDF, page : 24

03.
.

.

wikidocs.net PDF, page : 25

1)
,
. .

. "
" .
.
, , , ,
. .

wikidocs.net PDF, page : 26

[1] (Number)
.
. 123 , 12.34 ,
(1 + 2j) , 8 16 .
.

---------------------------------123,-345,0
123.45,-1234.5,3.4e10
1+2j,-3j
8034,025
160x2A,0xFF

(Integer)
. a .
, 0 .

>>>a=123
>>>a=-178
>>>a=0

(Floating-point)
.
. 4.24e10 4.24E10 . (e,
E .)

>>>a=1.2
>>>a=-3.45
>>>a=4.24E10#4.24*1010
>>>a=4.24e-10#4.24*1010

wikidocs.net PDF, page : 27

8 (Octal)
8 0( 0) .

>>>a=0177

16 (Hexadecimal)
16 0x .

>>>a=0x8ff
>>>b=0xABC

8 16 .

(Complex number)
j i . i j
. j 'J' .

>>>a=1+2j
>>>b=3-4J

.
. .
.
.real .

>>>a=1+2j
>>>a.real
1.0

.imag .

wikidocs.net PDF, page : 28

>>>a=1+2j
>>>a.imag
2.0

.conjugate() .

>>>a=1+2j
>>>a.conjugate()
(1-2j)

abs() . (1+2j 1^2+2^2 .)

>>>a=1+2j
>>>abs(a)
2.2360679774997898


(+, -, *, /) .
.

>>>a=3
>>>b=4
>>>a+b
7
>>>a*b
12

'/'. 3 / 4 0.75
.
.

>>>3/4
0

wikidocs.net PDF, page : 29

>>>3/4.0
0.75
>>>3.0/4
0.75

. float .

>>>a=3
>>>b=4
>>>float(a)/b
0.75

. , float(a) a 3
3.0 . 4
.

** . x ** y x y
. .

>>>a=3
>>>b=4
>>>a**b
81

% . %
. 7 3 1 3 7 3 .
.

>>>7%3
1
>>>3%7
3

wikidocs.net PDF, page : 30

[2] (String)
. .

"Lifeistooshort,YouneedPython"
"a"
"123"

() . 123"
? ()
.

4
()
. .

HelloWorld
'Pythonisfun'
"""Lifeistooshort,Youneedpython"""
'''Lifeistooshor,Youneedpython'''

()
(') (""", ''')
.
? .

(') (")
(') ("). (') (")
. .
.

1) (')

Python'sfavoritefoodisperl

wikidocs.net PDF, page : 31


1 . Python's (')
. (" ") . (" ")
(') .

>>>food="Python'sfavoritefoodisperl"

(") (') . 'Python'


(Syntax Error) .

>>>food='Python'sfavoritefoodisperl'

2) (")

"Pythonisveryeasy."hesays.

2 (") (") ?
(' ') .

>>>say='"Pythonisveryeasy."hesays.'

(' ') (")


.

3) \() (') (")

>>>food='Python\'sfavoritefoodisperl'
>>>say="\"Pythonisveryeasy.\"hesays."

(') (") '\'() . (\')


(')
. (\") . .
.

wikidocs.net PDF, page : 32



.
?

Lifeistooshort
Youneedpython
Pythonispowerfullanguage

?
1) '\n'

>>>multiline="Lifeistooshort\nYouneedpython\nPythonispowerfullanguage"

'\n'
. () .

2) (""")

multiline=
Lifeistooshort
Youneedpython
Pythonispowerfullanguage

[]
'\n'
.
,
.
.

wikidocs.net PDF, page : 33

---------------------------------------
---------------------------------------\n()
\v
\t
\r
\f
\a
\b
\000
\\"\"
\'(')
\"(")
---------------------------------------\n,\t,\\,\',\".
.


.
. .
.
1) (Concatenation)

>>>head="Python"
>>>tail="isfun!"
>>>printhead+tail
Pythonisfun!

1 . . Python"
head " is fun" tail . Python is fun!. , head
tail "+" .
.
2)

wikidocs.net PDF, page : 34

>>>a="python"
>>>printa*2
pythonpython

* .
* .
. "print a * 2" a .

. .

#multistring.py
print"="*50
print"MyProgram"
print"="*50

==================================================
MyProgram
==================================================

.
?


(indexing) , (slicing)
. .

>>>a="Lifeistooshort,YouneedPython"

Lifeistooshort,YouneedPython
0123

wikidocs.net PDF, page : 35

0123456789012345678901234567890123

. "Life is too short, You need Python"


'L' 0 'i' 1
. "short" s 12 .

>>>a="Lifeistooshort,YouneedPython"
>>>a[3]
'e'

a[3] a 'e' .
a[3] 3 .

, .

0 .

a[0]: 'L', a[1]: 'i', a[2]: 'f', a[3]: 'e', a[4]: ' ', a[5]: 'i', a[6]: 's',
a[7]: ' ',....

0 .
a[3] .
(Indexing) .
.

>>>a[0]
'L'
>>>a[12]
's'
>>>a[-1]
'n'

wikidocs.net PDF, page : 36

a[-1] ?
(-) . a[-1]
. a "Life is too short, You need Python"
'n' .
a[-0] ?
. 0 -0 a[-0] a[0]
.

>>>a[-0]
'L'

>>>a[-2]
'o'
>>>a[-5]
'y'


. "Life is too short, You need Python"
'Life' 'You' ?
.

>>>b=a[0]+a[1]+a[2]+a[3]
>>>b
'Life'

.
(Slicing) .
. ( -
>>> a = "Life is too
short, You need Python" )

>>>a[0:4]
'Life'

a[0:4] a , "Life is too short, You need Python" 0


4 . .

wikidocs.net PDF, page : 37

a[0] 'L', a[1] 'i', a[2] 'f', a[3] 'e' a[0:3] 'Life'
?
.

>>>a[0:3]
'Lif'

. a[: ]
.
a[0:3] .

0 <= a < 3

a a[0], a[1], a[2] . a[0:3] 'Lif' a[0:4]


'Life' .
.
.

>>>a[0:5]
'Life'

a[0] + a[1] + a[2] + a[3] + a[4] . a[4] ' '


'Life' 'Life ' . 'L', 'i' , 'f', 'e'
. 'Life' 'Life ' .
'0' .

>>>a[0:2]
'Li'
>>>a[5:7]
'is'
>>>a[12:17]
'short'

a[:] .

>>>a[19:]
'YouneedPython'

wikidocs.net PDF, page : 38

a[:] .

>>>a[:17]
'Lifeistooshort'

a[:]

>>>a[:]
'Lifeistooshort,YouneedPython'

a[:]
.
'-' .

>>>a[19:-7]
'Youneed'

a[19:-7] a[19] a[-7] . a[-7] .

>>>a="20010331Rainy"
>>>date=a[:8]
>>>weather=a[8:]
>>>date
'20010331'
>>>weather
'Rainy'

a . '8' a[:8], a[8:]


. a[:8] a[8] a[8:] a[8] 8
. "20010331Rainy"
'20010331' 'Rainy' .
"20010331Rainy" 2001 0331
Rainy .

wikidocs.net PDF, page : 39

>>>a="20010331Rainy"
>>>year=a[:4]
>>>day=a[4:8]
>>>weather=a[8:]
>>>year
'2001'
>>>day
'0331'
>>>weather
'Rainy'

4 8 "20010331Rainy" .
.
.

Pithon Python" ?
"Pithon" "Python" ?
.

>>>a="Pithon"
>>>a[1]
'i'
>>>a[1]='y'

a "Pithon" a[1] 'i'


a[1] 'y' . ?
.
. ? . .
"Pithon" "Python"
.

>>>a="Pithon"
>>>a[:1]
'P'
>>>a[2:]
'thon'

wikidocs.net PDF, page : 40

>>>a[:1]+'y'+a[2:]
'Python'

'Pithon' 'P' 'thon'


'y' 'Python' .

(Formatting)
, .
.

18.

20 .

20


. 20 18 .

.
.
.
1)

>>>print"Ieat%dapples."%3
Ieat3apples.

3
. 3 % . 3
"%d" .
. .
2)

wikidocs.net PDF, page : 41

>>>print"Ieat%sapples."%"five"
Ieatfiveapples.

%d
%s . .
%d %s .
3)

>>>number=3
>>>print"Ieat%dapples."%number
Ieat3apples.

1 3 .
.
?
4)

>>>number=10
>>>day="three"
>>>print"Ieat%dapples.soIwassickfor%sdays."%(number,day)
Ieat10apples.soIwassickforthreedays.

4 % ( )
.


4
. .

-------------------------------------------------
-------------------------------------------------%s (String)
%c (character)
%d (Integer)
%f (floating-point)

wikidocs.net PDF, page : 42

%o 8
%x 16
%% Literal % ( '%s' )
--------------------------------------------------

%s .
.

>>>print"Ihave%sapples"%3
Ihave3apples
>>>print"Todaysrateis%s"%3.234
Todaysrateis3.234

3 %d 3.234 %f
%s . %s %d, %f
. %s
.

[] %d % %%

>>>print"Erroris%d%."%98

"Error is 98%."
. %d %
% %% % .
. %d %
.

>>>print"Erroris%d%%."%98
Erroris98%.

wikidocs.net PDF, page : 43


%d, %s
. .
.
1)

>>>print"%10s"%"hi"
hi
^^^^^^^^^^

"%10s" 10
. "%-10s" . .

>>>print"%-10sjane."%'hi'
hijane.
^^^^^^^^^^

2)

>>>print"%0.4f"%3.42134234
3.4213

, 3.42134234 4 . '.'
4 . '.'
.

>>>print"%10.4f"%3.42134234
3.4213
^^^^

3.42134234 10 4
.
.

wikidocs.net PDF, page : 44

.

.
.

(upper)

>>>a="hi"
>>>a.upper()
'HI'


.
'.' . upper()
. .

(count)

>>>a="hobby"
>>>a.count('b')
2

b .

1(find)

>>>a="Pythonisbestchoice"
>>>a.find('b')
10

'b' .
-1 .

wikidocs.net PDF, page : 45

2(index)

>>>a="Lifeistooshort"
>>>a.index('t')
8

't' .
. find
.

(join)

>>>a=","
>>>a.join('abcd')
'a,b,c,d'

"abcd" a ',' .

(lower)

>>>a="HI"
>>>a.lower()
'hi'

(lstrip)

wikidocs.net PDF, page : 46

>>>a="hi"
>>>a.lstrip()
'hi'

. lstrip 'l'
left.

(rstrip)

>>>a="hi"
>>>a.rstrip()
'hi'

. rstrip 'r'
right.

(strip)

>>>a="hi"
>>>a.strip()
'hi'

(replace)

>>>a="Lifeistooshort"
>>>a.replace("Life","Yourleg")
'Yourlegistooshort'

replace( , )
.

wikidocs.net PDF, page : 47

(split)

>>>a="Lifeistooshort"
>>>a.split()
['Life','is','too','short']
>>>a="a:b:c:d"
>>>a.split(':')
['a','b','c','d']

a.split() .
a.split(':')
. . ['Life', 'is', 'too', 'short'] ['a',
'b', 'c', 'd'] .

(swapcase)

>>>a="Himan"
>>>a.swapcase()
'hIMAN'

.

. .
.
a ( a )

a.upper()
a.count(x)
a.find(x)
a.index(x)
a.join(s)
a.lower()

a .
a x .
a x
. -1 .
a x
. .
s
a .
a .

wikidocs.net PDF, page : 48

a.lstrip()
a.rstrip()
a.strip()
a.replace(s, r)
a.split([s])
a.swapcase()

a
a
a
a
.
a

.
.
.
s r
.

a ,
.

wikidocs.net PDF, page : 49

[3] (List)
.
. 1 10 1, 3, 5, 7, 9
. .
. .
1, 3, 5, 7, 9 .

>>>odd=[1,3,5,7,9]

([ ])
.

>>>a=[]
>>>b=[1,2,3]
>>>c=['Life','is','too','short']
>>>d=[1,2,'Life','is']
>>>e=[1,2,['Life','is']]

a ([]) b
, c d
e . ,
.


. .
.
.


a [1, 2, 3] .

>>>a=[1,2,3]
>>>a

wikidocs.net PDF, page : 50

[1,2,3]

>>>a[0]
1

a[0] 'a' .

a[0] a[2] .

>>>a[0]+a[2]
4

1 + 3 4 .

0 a[1] a
a[0] a . a[-1]
a .

>>>a[-1]
3

a 1, 2, 3 ['a', 'b', 'c']


.

>>>a=[1,2,3,['a','b','c']]

>>>a[0]
1

wikidocs.net PDF, page : 51

>>>a[-1]
['a','b','c']
>>>a[3]
['a','b','c']

a[-1] ['a', 'b', 'c'] . a[3] a


a[-1] .

a ['a', 'b', 'c'] 'a'


?
.

>>>a[-1][0]
'a'

'a' . a[-1] ['a', 'b', 'c']


[0] .

>>>a[-1][1]
'b'
>>>a[-1][2]
'c'

>>>a=[1,2,['a','b',['Life','is']]]

a ['a', 'b', ['Life', 'is']]


['Life', 'is'] . .

'Life' .

>>>a[2][2][0]
'Life'

wikidocs.net PDF, page : 52

a ['a', 'b', ['Life', 'is']]


['Life', 'is'] .
.


.
.
, .

>>>a=[1,2,3,4,5]
>>>a[0:2]
[1,2]

>>>a="12345"
>>>a[0:2]
'12'

.
.

>>>a=[1,2,3,4,5]
>>>b=a[:2]
>>>c=a[2:]
>>>b
[1,2]
>>>c
[3,4,5]

b a 2 . a[2]
'3' . c 2 .

wikidocs.net PDF, page : 53

>>>a=[1,2,3,['a','b','c'],4,5]
>>>a[2:5]
[3,['a','b','c'],4]
>>>a[3][:2]
['a','b']

a[3] ['a', 'b', 'c'] a[3][:2] ['a', 'b', 'c'] a[0]


a[2] , ['a', 'b'] .

(+) (*)
+ * .
.
1)

>>>a=[1,2,3]
>>>b=[4,5,6]
>>>a+b
[1,2,3,4,5,6]

+ . +
. "abc" + "def" = "abcdef" .

2)

>>>a=[1,2,3]
>>>a*3
[1,2,3,1,2,3,1,2,3]

[1, 2, 3]
. "abc" * 3 = "abcabcabc" .

wikidocs.net PDF, page : 54

- 1
4 .

1) 1

>>>a=[1,2,3]
>>>a[2]=4
>>>a
[1,2,4]

a[2] '3' '4' .

2) 2

>>>a[1:2]
[2]
>>>a[1:2]=['a','b','c']
>>>a
[1,'a','b','c',4]

a[1:2] a[1] a[2] a[2] a = [1, 2, 4]


2 . , a[1:2] ['a', 'b', 'c'] a 2 ['a',
'b', 'c'] .

- a[1] = ['a', 'b', 'c']


. a[1] = ['a', 'b', 'c'] a
['a', 'b', 'c'] a[1:2] a[1] a[2] ['a',
'b', 'c'] . a[1] = ['a', 'b', 'c']
a [1, ['a', 'b', 'c'], 4] .

3) 1

>>>a[1:3]=[]
>>>a
[1,'c',4]

wikidocs.net PDF, page : 55

a [1, 'a', 'b', 'c', 4]. a[1:3] a[1] a[3]


a[1:3] ['a', 'b']. a[1:3] []
a a ['a', 'b'] [1, 'c', 4] .

4) 2

>>>a
[1,'c',4]
>>>dela[1]
>>>a
[1,4]

del a[x] x . del


.

del

( - .)
del a[x:y] x y . 4 a[1]
.

[]
.

>>>a=[1,2,3]
>>>a[2]+"hi"
Traceback(innermostlast):
File"",line1,in?
a[2]+"hi"
TypeError:numbercoercionfailed

TypeError . ?a[2] 3
"hi" . ( )
. Type . .

wikidocs.net PDF, page : 56

'3hi' 3 '3'
.

>>>str(a[2])+"hi"
>>>`a[2]`+"hi"

str
(`) Back Quote , Back Quote(`) str
.


'.'
. .

(append)
append . append(x)
x .

>>>a=[1,2,3]
>>>a.append(4)
>>>a
[1,2,3,4]

.
.

>>>a.append([5,6])
>>>a

wikidocs.net PDF, page : 57

[1,2,3,4,[5,6]]

(sort)
sort .

>>>a=[1,4,3,2]
>>>a.sort()
>>>a
[1,2,3,4]

>>>a=['a','c','b']
>>>a.sort()
>>>a
['a','b','c']

>>>a=['abc',123,'youneedpython']
>>>a.sort()
>>>a
[123,'abc','youneedpython']


. 123 'abc' 'you need
python' 'a' 'y' 'a' 'y'
'abc' .

wikidocs.net PDF, page : 58

(reverse)
reverse .
. .

>>>a=['a','c','b']
>>>a.reverse()
>>>a
['b','c','a']

(index)
index(x) x .

>>>a=[1,2,3]
>>>a.index(3)
2
>>>a.index(1)
0

a 3 a[2] 2 , 1 a[0]
0 .

0 a .

>>>a.index(0)
Traceback(innermostlast):
File"",line1,in?
a.index(0)
ValueError:list.index(x):xnotinlist

Tracebace ValueError .

(insert)
insert(a, b) a b .

wikidocs.net PDF, page : 59

>>>a=[1,2,3]
>>>a.insert(0,4)
[4,1,2,3]

0 4 .

a a[3], 5 .

>>>a.insert(3,5)
[4,1,2,5,3]

(remove)
remove(x) x . a 3
3 .

>>>a=[1,2,3,1,2,3]
>>>a.remove(3)
[1,2,1,2,3]

3 .

>>>a.remove(3)
[1,2,1,2]

(pop)
pop() .

>>>a=[1,2,3]
>>>a.pop()
3
>>>a
[1,2]

a [1,2,3] 3 [1, 2]
.

wikidocs.net PDF, page : 60


pop(x) x .

>>>a=[1,2,3]
>>>a.pop(1)
2
>>>a
[1,3]

a.pop(1) a[1] .

(count)
count(x) x .

>>>a=[1,2,3,1]
>>>a.count(1)
2

1 a 2 .

(extend)
extend(x) x . a x .

>>>a=[1,2,3]
>>>a.extend([4,5])
>>>a
[1,2,3,4,5]

a.extend([4,5]) a + [4,5] .

.
a ( a .)

a.append(x)
a.sort()
a.reverse()

a x
a
a .

a.index(x)

a x

wikidocs.net PDF, page : 61

a.insert(i, x)
a.remove(x)

a.count(x)

a.extend(x)

a x ()

a.pop()

a i x
a x
a
a x

wikidocs.net PDF, page : 62

[4] (tuple)
.
. .
'[' ']' '(' ')' .
, , .

>>>t1=()
>>>t2=(1,)
>>>t3=(1,2,3)
>>>t4=1,2,3
>>>t5=('a','b',('ab','cd'))

, t2 =
(1,) (',') t4 = 1, 2, 3
() .
.
.
. .

.
.
.

, ,
.
1 .

1)

>>>t1=(1,2,'a','b')
>>>t1[0]
1
>>>t1[3]

wikidocs.net PDF, page : 63

'b'

, t1[0], t1[3] .

2)

>>>t1=(1,2,'a','b')
>>>t1[1:]
(2,'a','b')

3) ()

>>>t2=(3,4)
>>>t1+t2
(1,2,'a','b',3,4)

4) ()

>>>t2*3
(3,4,3,4,3,4)

() .

.
.
1)

>>>delt1[0]
Traceback(innermostlast):
File"",line1,in?delt1[0]

wikidocs.net PDF, page : 64

TypeError:objectdoesn'tsupportitemdeletion

del .
.

2)

>>>t1[0]='c'
Traceback(innermostlast):
File"",line1,in?t1[0]='c'
TypeError:objectdoesn'tsupportitemassignment

wikidocs.net PDF, page : 65

[5] (Dictionary)
= , =
. .
Associative array, Hash .
. , people , baseball
Key Value
. Key 'baseball' Value '' .
(sequential) key
value . key value . baseball
baseball
.

?
.

{Key1:Value1,Key2:Value2,Key3:Value3,,,,}

, Key Value '{' '}' Key : Value


(',') .

>>>dic={'name':'pey','phone':'0119993323','birth':'1118'}

key name, phone, birth value pey,


0119993323, 1118 .

.
< dic >
key
name
phone

value
pey
01199993323

birth

1118

wikidocs.net PDF, page : 66

>>>a={1:'hi'}

Key 1 Value 'hi' .

>>>a={'a':[1,2,3]}

Value .


? . 4
.
.
.

{:,:,:,:}

. ?
.
.

Key Value
.

>>>grade={'pey':10,'julliet':99}
>>>grade['pey']
10
>>>grade['julliet']
99


. Key Value .

wikidocs.net PDF, page : 67

Value "[Key]" Value .

>>>a={1:'a',2:'b'}
>>>a[1]
'a'
>>>a[2]
'b'

a {1:'a', 2:'b'} . a[1] 'a'


. a[1] a[1] . [
] 1 Key 1 .
. a[1] {1:'a', 2:'b'}
Key 1 Value 'a' . a[2] .

>>>a={'a':1,'b':2}
>>>a['a']
1
>>>a['b']
2

a Key Value
. a['a'], a['b'] Key Value .
a a[Key] Key Value .

Key Value .

>>>dic={'name':'pey','phone':'0119993323','birth':'1118'}
>>>dic['name']
'pey'
>>>dic['phone']
'0119993323'
>>>dic['birth']
'1118'

wikidocs.net PDF, page : 68

,
Key Value Key Value
. 1 3 .
. .
.

.
1) 1

>>>a={1:'a'}
>>>a[2]='b'
>>>a
{2:'b',1:'a'}

{1: 'a'} a[2] = 'b' 2 : 'b' .

2) 2

>>>a['name']='pey'
{'name':'pey',2:'b',1:'a'}

a 'name': 'pey' .

3) 3

>>>a[3]=[1,2,3]
{'name':'pey',3:[1,2,3],2:'b',1:'a'}

Key 3 Value [1, 2, 3] .

4) 1

>>>dela[1]
>>>a
{'name':'pey',3:[1,2,3],2:'b'}

wikidocs.net PDF, page : 69

4 . del a[key] key:value


.


Key
. Key
1:'a' .
. Key .

>>>a={1:'a',1:'b'}
>>>a
{1:'b'}

Key:Value Key
Value Key Key Value
.
Key . Key
. Key Key
. Key Key
. Key TypeError .

>>>a={[1,2]:'hi'}
Traceback(mostrecentcalllast):
File"",line1,in?
TypeError:unhashabletype

Key . Value
.

Key (keys)

wikidocs.net PDF, page : 70

>>>a={'name':'pey','phone':'0119993323','birth':'1118'}
>>>a.keys()
['birth','name','phone']

a.keys() a Key .
.
['birth', 'name', 'phone'] . Key value
.

Value (values)

>>>a.values()
['1118','pey','0119993323']

value a.values() values .

Key, Value (items)

>>>a.items()
[('birth','1118'),('name','pey'),('phone','011993323')]

items key value .

Key: Value (clear)

>>>a.clear()
>>>a
{}

clear() . [] ()
{} .

Key Value (get)

wikidocs.net PDF, page : 71

>>>a={'name':'pey','phone':'0119993323','birth':'1118'}
>>>a.get('name')
'pey'
>>>a.get('phone')
'0119993323'

get(x) x key value . a.get('name')


a['name'] .
.

Key (has_key)

>>>a={'name':'pey','phone':'0119993323','birth':'1118'}
>>>a.has_key('name')
True
>>>a.has_key('email')
False

a.has_key(x) a x key , 1
0 .

.
( a .)

a.keys()

a.values()

a.items()
a.clear()
a.get(x)
a.has_key(x)

a Key
.
a Value
.
a (Key, Value)
.
a Key:Value .
a Key x Value .
a x Key ,
.

, , , ,
. 50%
. .

.

wikidocs.net PDF, page : 72

wikidocs.net PDF, page : 73

[6]
?
. .
.

or

"" (: "python")
""
[] (: [1,2.3])

[]
()
{}
0 (: 1)
0

None

, , , ("", [], (), {}) .


. 0 . None
. None
.

>>>a=[1,2,3,4]
>>>whilea:
...a.pop()
...
4
3
2
1

a = [1,2,3,4] .

while .

while<>:
<>

wikidocs.net PDF, page : 74

<> < > . , a


a.pop() . a.pop() a
a ( )
. a ([]) .
while .
.

>>>if[]:
...print"True"
...else:
...print"False"
...
False

if .
(if .) [] "True"
"False" . []
False" .

>>>if[1,2,3]:
...print"True"
...else:
...print"False"
...
True

. [1,2,3] "True"
"False" . [1,2,3] .
"True" .

wikidocs.net PDF, page : 75

[7]
. a, b, c .

>>>a=1
>>>b="python"
>>>c=[1,2,3]

'='(assignment) .


. .

.
.

>>>a=3

a = 3 3 ()
. a 3
. , a (Reference).

a --> 3

, a 3 .

>>>a=3
>>>b=3
>>>aisb

wikidocs.net PDF, page : 76

True

a 3 b 3 . a = 3 3
a 3 . b 3 .

3 2 .
. is
a is b (True) . 3
2. (Reference Count, ) 2
. c = 3 3 .


3 . ?
3 , 0
3 . 3
3 . -
(Garbage collection) .

>>>a=3
>>>b=3
>>>del(a)
>>>del(b)

a b 3 del
a, b 0 3
.


1)

>>>a,b='python','life'

wikidocs.net PDF, page : 77

1 a, b . 2 .

2)

>>>(a,b)=('python','life')

1 2 . .

3)

>>>[a,b]=['python','life']

3 .

4)

>>>a=b='python'

>>>a=3
>>>b=5
>>>a,b=b,a
>>>a
5
>>>b
3

a 3, b 5 a, b = b, a
.

wikidocs.net PDF, page : 78


.
.

>>>a=[1,2,3]
>>>b=a
>>>a[1]=4
>>>a
[1,4,3]
>>>b
[1,4,3]

b a . , a
a[1] 4 , a b .
a, b [1, 2, 3] . a, b
.

b a a
? .

1) [:]
[:] .

>>>a=[1,2,3]
>>>b=a[:]
>>>a[1]=4
>>>a[1,4,3]
>>>b[1,2,3]

a b .

2) copy
copy . from copy import copy
2 .
copy .

wikidocs.net PDF, page : 79

>>>fromcopyimportcopy
>>>b=copy(a)

b = copy(a) b = a[:] .

.
, is .
.

>>>bisa
False

b is a False b a .

wikidocs.net PDF, page : 80

2)
if, while, for .
. , ,
, . .
, ,
. ,
, .

wikidocs.net PDF, page : 81

[1] if
.

.

.
if.

>>>money=1
>>>ifmoney:
...print""
...else:
...print""
...

if
if else .

if<>:
<1>
<2>
...
else:
<A>
<B>
...

if else
.

wikidocs.net PDF, page : 82

(indentation)
if if <>: if
.

if<>:
<1>
<2>
<3>

< 1> < 2>,


< 3> .
.

if<>:
<1>
<2>
<3>

< 2> .

if<>
<1>
<2>
<3>

< 3> < 1> < 2>


. .
? ?
,
, .
.
. .

wikidocs.net PDF, page : 83

[] ':'
if() ':' .
. ':'
Guido . while for, def, class
':' . ':'
.

':'
(indentation) .
.

if { }
.

?
if <> .
.

"abc"

""

[1,2,3]

[]

(1,2,3)

()

{"a":"b"}

{}

>>>money=1
>>>ifmoney:

wikidocs.net PDF, page : 84

money money 1 if
.

(<, >, ==, !=, >=, <=)


. .
x < y

x y

x > y

x y

x == y

x y

x != y

x y

x >= y

x y

x <= y

x y

>>>x=3
>>>y=2
>>>x>y
True
>>>

x 3 y 2 x > y True .
x > y .

>>>x<y
False

False .

wikidocs.net PDF, page : 85

>>>x==y
False

x y . .

>>>x!=y
True

x y . .

3000

>>>money=2000
>>>ifmoney>=3000:
...print""
...else:
...print""
...

>>>

money >= 3000 else .

and, or, not


and, or, not .

wikidocs.net PDF, page : 86

x or y

x y

x and y

x y

not x

" 3000

>>>money=2000
>>>watch=1
>>>ifmoney>=3000orwatch:
...print""
...else:
...print""
...

>>>

money 2000 watch 1 money >= 3000 or watch


if . watch = 1
. .
watch = 0 .

x in s, x not in s
. .
x in , x not in
x in , x not in
x in , x not in

'in' '~'
.

wikidocs.net PDF, page : 87

>>>1in[1,2,3]
True
>>>1notin[1,2,3]
False

[1, 2, 3] 1 ? . 1 [1, 2,
3] True . "[1, 2, 3] 1
? . 1 [1, 2, 3] False .

>>>'a'in('a','b','c')
True
>>>'j'notin'python'
True

.
" ,

>>>pocket=['paper','handphone','money']
>>>if'money'inpocket:
...print""
...else:
...print""
...

>>>

['paper', 'handphone', 'money'] 'money' 'money' in pocket


if .

elif ( )
if else . if
else .

wikidocs.net PDF, page : 88

" , ,

.
.

if else .

>>>pocket=['paper','handphone']
>>>watch=1
>>>if'money'inpocket:
...print""
...else:
...ifwatch:
...print""
...else:
...print""
...

>>>

.
elif .

elif .

>>>pocket=['paper','handphone']
>>>watch=1
>>>if'money'inpocket:
...print""
...elifwatch:
...print""
...else:
...print""
...

wikidocs.net PDF, page : 89

, elif if <>: <> . if, elif, else


.

If<>:
<1>
<2>
...
elif<>:
<1>
<2>
...
elif<>:
<1>
<2>
...
...
else:
<1>
<2>
...

elif . (: C switch
.)

pass

. .

"

pass .

>>>pocket=['paper','money','handphone']
>>>if'money'inpocket:
...pass
...else:
...print""
...

wikidocs.net PDF, page : 90

pocket 'money' if pass


.

if
if else .
. pass
.

>>>pocket=['paper','money','handphone']
>>>if'money'inpocket:pass
...else:print""
...

if ':' . else .
.

wikidocs.net PDF, page : 91

[2] while
while .

while .

while<>:
<1>
<2>
<3>
...

while .

>>>treeHit=0
>>>whiletreeHit<10:
...treeHit=treeHit+1
...print"%d."%treeHit
...iftreeHit==10:
...print"."
...
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
.

while treeHit < 10 . treeHit 10 while


. whlie treeHit = treeHit + 1
treeHit 1 . treeHit
treeHit 10 treeHit < 10
while .

wikidocs.net PDF, page : 92

treeHit = treeHit +1 treeHit


1 . treeHit += 1 .

(Loop)
. .
while .
.
.

while1:
<1>
<2>
...

while "1" . while while


while .

>>>while1:
...print"Ctrl-Cwhile."
...
Ctrl-Cwhile.
Ctrl-Cwhile.
Ctrl-Cwhile.
....

. Ctrl-C .
. .

>>>prompt="""
...1.Add
...2.Del
...3.List
...4.Quit

wikidocs.net PDF, page : 93

...
...Enternumber:"""
>>>

>>>number=0
>>>whilenumber!=4:
...printprompt
...number=int(raw_input())
...
1.Add
2.Del
3.List
4.Quit
Enternumber:

number "0" . while


number != 4 number number
. while number 4 prompt
. 4 prompt
. number = int(raw_input())
. int raw_input .

while (break)
while while .
while .
.
while .
.
while
. while
break.

wikidocs.net PDF, page : 94

) break

>>>coffee=10
>>>money=300
>>>whilemoney:
...print"."
...coffee=coffee-1
...print"%d."%coffee
...ifnotcoffee:
...print".."
...break
...

money 300 while money: money 0


. . while coffee =
coffee - 1 coffee . coffee 0 if not
coffee: not coffee if break
while .

.
. .
.

#-*-coding:euc-kr-*-
#coffee.py
coffee=10
while1:
money=int(raw_input(":"))
ifmoney==300:
print"."
coffee=coffee-1
elifmoney>300:
print"%d."%(money-300)
coffee=coffee-1
else:
print"."
print"%d."%coffee
ifnotcoffee:
print".."
break

wikidocs.net PDF, page : 95

.
if while . money = int(raw_input( :
)) money
.
1
.

while (continue)
while while
while . 1
10 while .
?

) continue

>>>a=0
>>>whilea<10:
...a=a+1
...ifa%2==0:continue
...printa
...
1
3
5
7
9

1 10 . a 10 a 1
. if a % 2 == 0 (2 0 ) a
. , a continue . continue while
. a print a .

wikidocs.net PDF, page : 96

[3] for
for. for
.

for
for .

forin(,):
<1>
<2>
...

< 1>, <


2>,,, .

for
for . .

1) for

>>>test_list=['one','two','three']
>>>foriintest_list:
...printi
...
one
two
three

['one', 'two', 'three'] 'one' i print i


. 'two' i print i
.

for .

wikidocs.net PDF, page : 97

5 60
. .

5 .

mark=[90,25,67,45,80]

1 90 5 80.


. .

#marks1.py
marks=[90,25,67,45,80]
number=0
formarkinmarks:
number=number+1
ifmark>=60:
print"%d."%number
else:
print"%d."%number

number . marks
mark for . for
number 1 mark 60 60
.

for continue
while continue for . , for
continue for .

60
.

wikidocs.net PDF, page : 98

#marks2.py
marks=[90,25,67,45,80]
number=0
formarkinmarks:
number=number+1
ifmark<60:continue
print"%d.."%number

60 mark < 60 continue .


print for .

for range
for range .
range .

>>>a=range(10)
>>>a
[0,1,2,3,4,5,6,7,8,9]

range(10) 0 9 .

. .

>>>a=range(1,11)
>>>a
[1,2,3,4,5,6,7,8,9,10]

for range 1 10 .
) 1 10

>>>sum=0
>>>foriinrange(1,11):

wikidocs.net PDF, page : 99

...sum=sum+i
...
>>>printsum
55

range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .


i sum = sum + i
sum 55 .

60 range
. .

#marks3.py
marks=[90,25,67,45,80]
fornumberinrange(len(marks)):
ifmarks[number]<60:continue
print"%d.."%(number+1)

len len .
len(marks) 5 range(len(marks)) range(5) . number
0 4 makrs[number] 90, 25, 67, 45, 80
.

for

>>>a=[(1,2),(3,4),(5,6)]
>>>for(first,last)ina:
...printfirst+last
...
3
7
11

a (first, last)
.

wikidocs.net PDF, page : 100

>>>(first,last)=(1,2)

for range
for range 4 .

>>>foriinrange(2,10):
...forjinrange(1,10):
...printi*j,
...print'\n'
...
24681012141618
369121518212427
4812162024283236
51015202530354045
61218243036424854
71421283542495663
81624324048566472
91827364554637281

for . range(2, 10) [2, 3, 4, 5, 6, 7, 8, 9]


i . i 2 for . range(1, 10) [1, 2, 3, 4,
5, 6, 7, 8, 9] j print i*j .
i 2 2*1, 2*2, 2*3, , , ,2*9 . i
3 2 i 9 .
print i*j, print i*j (',')
.
. print '\n' 2, 3, , for
.

if, while, for . while


for . for while
while for .
.

wikidocs.net PDF, page : 101

04.
, ,
.

.
.

, API
.

wikidocs.net PDF, page : 102

1)
. .
.
. () .
?

(by http://www.wpclipart.com)

.
, .
.
. .
y = 2x + 3 .
x y
.
.

?
.
.
. ,
.

.
.

.
.

wikidocs.net PDF, page : 103

def():
<1>
<2>
...

def


. .
.
. . if, while, for
.

defsum(a,b):
returna+b

sum
.

return . .

>>>defsum(a,b):
...returna+b
...
>>>

sum .

wikidocs.net PDF, page : 104

>>>a=3
>>>b=4
>>>c=sum(a,b)
>>>printc
7

a 3, b 4 sum a b c
. print c c .


.
.
, , ,
. .
.

---> () ---->


.
.

def():
<>
...
return

wikidocs.net PDF, page : 105

defsum(a,b):
result=a+b
returnresult

. . sum .

>>>defsum(a,b):
...result=a+b
...returnresult
...
>>>

>>>a=sum(3,4)
>>>printa
7

= (1, 2, , ,)


? . .

>>>defsay():
...return'Hi'
...
>>>

wikidocs.net PDF, page : 106

say .
.

? .

>>>a=say()
>>>printa
Hi

say() .
'Hi' . a = say() a 'Hi'
.

, .

= ()


. .

>>>defsum(a,b):
...print"%d,%d%d."%(a,b,a+b)
...
>>>

>>>sum(3,4)
3,47.

, .

wikidocs.net PDF, page : 107

(1, 2, , ,)

>>>a=sum(3,4)
3,47.

. "3, 4 7.
? print
. . return
.

a
.

>>>printa
None

a None. None .
sum a = sum(3, 4) sum
a None . .


. .

>>>defsay():
...print'Hi'
...
>>>

return .

wikidocs.net PDF, page : 108

>>>say()
Hi

, .

()

?
.
.
.

def (*):
< >
...

* .

. sum_many(1,2) 3 sum_many(1,2,3) 6
sum_many(1,2,3,4,5,6,7,8,9,10) 55 .

>>>defsum_many(*args):
...sum=0
...foriinargs:
...sum=sum+i
...returnsum
...
>>>

sum_many . args
. sum_many(1, 2, 3)
args (1, 2, 3) sum_many(1,2,3,4,5,6,7,8,9,10) args (1, 2, 3, 4, 5, 6, 7, 8,
9, 10) . *args . *pey, *python
. args arguments
.

wikidocs.net PDF, page : 109

>>>result=sum_many(1,2,3)
>>>printresult
6
>>>result=sum_many(1,2,3,4,5,6,7,8,9,10)
>>>printresult
55

def sum_many(*args) *args . .

>>>defsum_mul(choice,*args):
...ifchoice=="sum":
...result=0
...foriinargs:
...result=result+i
...elifchoice=="mul":
...result=1
...foriinargs:
...result=result*i
...returnresult
...
>>>

choice *args . .
sum_mul('sum', 1,2,3,4) sum_mul('mul', 1,2,3,4,5) choice 'sum' 'mul'
.

>>>result=sum_mul('sum',1,2,3,4,5)
>>>printresult
15
>>>result=sum_mul('mul',1,2,3,4,5)
>>>printresult
120

wikidocs.net PDF, page : 110


.
.

>>>defsum_and_mul(a,b):
...returna+b,a*b

>>>a=sum_and_mul(3,4)

a+b a*b a ?
. . .
.

a sum_and_mul .

a=(7,12)

, (7, 12) .
.

>>>sum,mul=sum_and_mul(3,4)

sum, mul = (7, 12) sum 7 mul 12


.

, .

>>>defsum_and_mul(a,b):
...returna+b
...returna*b
...
>>>

wikidocs.net PDF, page : 111

?
.

>>>defsum_and_mul(a,b):
...returna+b
...
>>>

, return return .

return
return .
.

>>>defsay_nick(nick):
...ifnick=="":
...return
...print"%s."%nick
...
>>>

nick .
. ( . ,
return .) ''
.
return .


.
.

defsay_myself(name,old,sex=1):
print"%s."%name
print"%d."%old

wikidocs.net PDF, page : 112

ifsex:
print"."
else:
print"."

( - '>>>' .)
. . sex=1
. .

.

say_myself("",27)
say_myself("",27,1)

, 27 name " old 27 sex


1 .
.

say_myself("",27,0)

0 sex 0 .

defsay_myself(name,sex=1,old):
print"%s."%name
print"%d."%old
ifsex:
print"."

wikidocs.net PDF, page : 113

else:
print"."

.
.

say_myself(,27)

name "
sex 27 old 27 .

SyntaxError: non-default argument follows default argument


. (name, old, sex=1) (name, sex=1, old)
. .


?
.

a=1
defvartest(a):
a=a+1
vartest(a)
printa

wikidocs.net PDF, page : 114

a 1 . 1
vartest a . a .
vartest a 1 2
1 .
. def
vartest(a) a
a .

a vartest b vartest
.

defvartest(b):
b=b+1

.
vartest a 1 1 a 2
a a .

defvartest(a):
a=a+1
vartest(3)
printa

?
. vartest(3) vartest a 4
print a . a
.
. .

vartest a 1 ?
. .

wikidocs.net PDF, page : 115

a=1
defvartest(a):
a=a+1
returna
a=vartest(a)
printa

return . vartest 1
. a = vartest(a) a vartest .
vartest a a .

a=1
defvartest():
globala
a=a+1
vartest()
printa

global . vartest global


a a .
global . .
. global
. .

wikidocs.net PDF, page : 116

2)

.
() () .

---> (, ) --->

.
.

input

>>>a=input()
'Lifeistooshort,youneedpython'
>>>a
Lifeistooshort,youneedpython
>>>a=input()
3
>>>a
3
>>>

input . input
(') (") . (
.) 3 (') (") .

>>>a=input()
youneedpython
Traceback(mostrecentcalllast):
File"",line1,in?
File"",line1

wikidocs.net PDF, page : 117

youneedpython
^
SyntaxError:invalidsyntax

you need python 'you need python' ''


.

raw_input

>>>a=raw_input()
Lifeistooshort,youneedpython
>>>a
Lifeistooshort,youneedpython
>>>

raw_input . (') (") .


raw_input .

raw_input input ?
input . ,
. raw_input
. .

>>>a=raw_input()
3
>>>a
'3'
>>>

3 a '3' .
raw_input .
.
raw_input ( )
. 3 .

wikidocs.net PDF, page : 118

input(prompt), raw_input(prompt)

.
. input raw_input .
.

>>>number=raw_input(":)
:

print
print .
print .

>>>a=123
>>>printa
123
>>>a="Python"
>>>printa
Python
>>>a=[1,2,3]
>>>printa
[1,2,3]

print .
(") +

>>>print"life""is""tooshort"--------------------
lifeistooshort
>>>print"life"+"is"+"tooshort"--------------------
lifeistooshort

wikidocs.net PDF, page : 119

. ,
'+' .

>>>print"life","is","tooshort"
lifeistooshort

(,) .


print (,)
.

>>>foriinrange(10):
...printi,
...
0123456789

wikidocs.net PDF, page : 120

3)
,
.
. .
,
.

#file1.py
f=open(".txt",'w')
f.close()

open .

open
.

= open(, )

wikidocs.net PDF, page : 121

,
. .txt"
".txt"
.

.txt" C:\Python
.

f=open("C:\Python\.txt",'w')

f.close() .
.
. .
.


.
.

#file2.py
f=open(".txt",'w')
foriinrange(1,11):
data="%d.\n"%i
f.write(data)
f.close()

foriinrange(1,11):
data="%d.\n"%i
printdata

data .

. . print f

wikidocs.net PDF, page : 122

write .
.txt" .
. .

.txt

1 .
2 .
3 .
4 .
5 .
6 .
7 .
8 .
9 .
10 .


. .


readline() . .

#file2.py
f=open(".txt",'r')
line=f.readline()
printline
f.close()

".txt"
.txt" . f.open(".txt",
'r') f . f

wikidocs.net PDF, page : 123

readline()
line .

#file3.py
f=open(".txt",'r')
while1:
line=f.readline()
ifnotline:break
printline

f.close()

while 1 f.readline() .
break . f.readline()
.

while1:
data=raw_input()
ifnotdata:break
printdata

.
. .
.


readlines() . .

#file4.py
f=open(".txt",'r')
lines=f.readlines()

wikidocs.net PDF, page : 124

forlineinlines:
printline
f.close()

f.readlines()
. lines [1 .,2 .,
, , 10 .] . f.readlines() f.readline() 's'
.


read() . .

#file5.py
f=open(".txt",'r')
data=f.read()
printdata
f.close()

f.read() . data .


w
.
('a') . .

#file6.py
f=open(".txt",'a')
foriinrange(11,20):
data="%d.\n"%i
f.write(data)

wikidocs.net PDF, page : 125

f.close()

.txt" ('a') ,
write .
.txt" .
.txt"
.

[] tell seek
tell seek . tell
, seek
.
. .

>>>f=open("test.txt",'w')
>>>f.write("thisisoneline\n")
>>>f.write("twoline\n")
>>>f.write("threeline\n")
>>>f.close()

test.txt write
test.txt .
test.txt .

this is one line


two line
three line

>>>f=open("test.txt",'r')
>>>f.tell()
0

wikidocs.net PDF, page : 126

, tell
. 0 .

>>>f.readline()
'thisisoneline\n'
>>>f.tell()
18

.
.
tell 18 .

>>>f.readline()
'twoline\n'
>>>f.tell()
28

28 .

>>>f.seek(0)
>>>f.readline()
'thisisoneline\n'
>>>

seek . f.seek(0)
0 .
.

sys
.

wikidocs.net PDF, page : 127

C:\> type a.txt

type .

[1 2]

. ()
. .

sys . sys
import sys import .
.

#sys1.py
importsys
args=sys.argv[1:]
foriinargs:
printi

C:\Python
.

C:\Python>python sys1.py aaa bbb ccc

.
:

aaa
bbb
ccc

wikidocs.net PDF, page : 128


sys argv . , argv[0]
sys1.py argv[1] argv .
for .

#sys2.py
importsys
args=sys.argv[1:]
foriinargs:
printi.upper(),

upper()
. . (: sys2.py C:\Python
.)

C:\Python> python sys2.py life is too short, you need python

LIFE IS TOO SHORT, YOU NEED PYTHON

wikidocs.net PDF, page : 129

05.
,
.

.

wikidocs.net PDF, page : 130

1)
(class) .
.

.

classSimple:
pass

.
(instance) . (
. )

?

. .

a=Simple()

Simple() a .
.


.
""
.
.

wikidocs.net PDF, page : 131


(, ) .
() ( ) ( )
( ) .
( ),
( ) .


.
.
.

>>>classService:
...secret=".

Service. Service
. .
.

wikidocs.net PDF, page : 132

>>>pey=Service()

pey Service .
Service .

pey .

>>>pey.secret
"

secret '.'( )
.


Service
.
.
.

>>>classService:
...secret=""
...defsum(self,a,b):
...result=a+b
...print"%s+%s=%s."%(a,b,result)
...
>>>

.
.

wikidocs.net PDF, page : 133

>>>pey=Service()

>>>pey.sum(1,1)
1+1=2.

.
.
. .

...defsum(self,a,b):
...result=a+b
...print"%s+%s=%s."%(a,b,result)


sum self
.

>>>pey=Service()
>>>pey.sum(1,1)

pey sum
. Service (sum)
.
.
. . ... pey
. , .

sum . sum
.

wikidocs.net PDF, page : 134

...defsum(self,a,b):
...result=a+b
...print"%s+%s=%s."%(a,b,result)

sum self
. sum 3.

pey sum .

pey.sum(pey,1,1)

sum .
pey sum pey
. sum pey
.

sum pey .

>>>pey.sum(1,1)

pey.sum(pey, 1, 1) pey.sum(1, 1) .
? pey.sum(1, 1) self
(, pey ) .

[] self .
'self' .

" self ."

self
.

wikidocs.net PDF, page : 135


. 1 + 2 = 3
. .
Service
.
Service . sum
.

>>>classService:
...secret=""
...defsetname(self,name):
...self.name=name
...defsum(self,a,b):
...result=a+b
...print"%s%s+%s=%s."%(self.name,a,b,result)
...
>>>

.
.

pey .

>>>pey=Service()

pey .

>>>pey.setname()

>>>pey.sum(1,1)
1+1=2.

wikidocs.net PDF, page : 136

.
setname .

...defsetname(self,name):
...self.name=name

pey

>>>pey=Service()

>>>pey.setname(")

setname .

pey '' .
pey ''
.

self.

pey " setname


.

self.name=name

self pey .

pey.name=name

wikidocs.net PDF, page : 137

name " .

pey.name="

pey .
pey .

1 + 1 = 2 .
.

...defsum(self,a,b):
...result=a+b
...print"%s%s+%s=%s."%(self.name,a,b,result)

1 + 1 = 2 . sum ,
self.name . self.name ?
sum .

pey " sum


.

>>>pey=Service()
>>>pey.setname()
>>>pey.sum(1,1)

sum .

pey .
. , '',
.

sum pey
? . setname
setname pey.name
. sum self.name pey.name sum pey
.

wikidocs.net PDF, page : 138

__init__ ?
, .
.
. .

>>>babo=Service()
>>>babo.sum(1,1)

babo.setname()

. .

babo.setname(") .

__init__
. .

>>>classService:
...secret=""
...def__init__(self,name):
...self.name=name
...defsum(self,a,b):
...result=a+b
...print"%s%s+%s=%s."%(self.name,a,b,result)
...
>>>

Service . setname
setname __init__ . __init__
. .
. , .

>>>pey=Service()

wikidocs.net PDF, page : 139

pey = Service() __init__ pey =


Service() .

>>>pey=Service()
>>>pey.setname()
>>>pey.sum(1,1)

__init__ .

>>>pey=Service()
>>>pey.sum(1,1)


.
self .
self ,
__init__ . pey = Service()
pey .
.


.
. .
.
(Instance)
.
(Instance) .
. ,
() . , ,
.
.
.
2 . .
.

wikidocs.net PDF, page : 140

class[()]:
<1>
<2>
...
def1(self[,1,2,,,]):
<1>
<2>
...
def2(self[,1,2,,,]):
<1>
<2>
...
...

class
. .
. .
.


.
. , , ,
. .

FourCal . a =
FourCal() a .

>>>a=FourCal()

wikidocs.net PDF, page : 141

a.setdata(4, 2) 4 2 a

>>>a.setdata(4,2)

a.sum() (4 + 2)

>>>printa.sum()
6

a.mul() (4 * 2)

>>>printa.mul()

a.sub() (4 - 2)

>>>printa.sub()
2

a.div() (4 / 2) .

>>>printa.div()
2

FourCal .

-

.

wikidocs.net PDF, page : 142

.

.

! . a = FourCal()
. . .

>>>classFourCal:
...pass
...
>>>

pass FourCal .
a = FourCal() a
. .

>>>a=FourCal()
>>>type(a)
<type'instance'>

a = FourCal() a type(a) a
. a . ( type .)
a . , ,
, .
a
.

(4, 2) .

>>>a.setdata(4,2)

wikidocs.net PDF, page : 143

>>>classFourCal:
...defsetdata(self,first,second):
...self.first=first
...self.second=second
...
>>>

FourCal pass setdata


. . .
( setdata FourCal . ) setdata
.

defsum(a,b):
returna+b

. . setdata
.

defsetdata(self,first,second):
self.first=first
self.second=second

self, first, second .


. self
.

>>>a=FourCal()
>>>a.setdata(4,2)

a a.setdata(4,2) FourCal
setdata setdata a
.

wikidocs.net PDF, page : 144

setdata self, first, second a.setdata(4,2)


a setdata self
.

self:a,first:4,second:2

. setdata 3
a.setdata(4,2) ? .
.

.
setdata .

self.first=first
self.second=second

. first 4 second 2
.

self.first=4
self.second=2

self. self a.setdata(4, 2)


a . self.first ?
a.first . self.second a.second .

a.first=4
a.second=2

wikidocs.net PDF, page : 145

>>>a=FourCal()
>>>a.setdata(4,2)
>>>printa.first
4
>>>printa.second
2

>>>classFourCal:
...defsetdata(self,first,second):
...self.first=first
...self.second=second
...
>>>

4 .
.
. !
.

>>>a=FourCal()
>>>a.setdata(4,2)
>>>printa.sum()
6

FourCal .

>>>classFourCal:
...defsetdata(self,first,second):
...self.first=first
...self.second=second
...defsum(self):
...result=self.first+self.second
...returnresult

wikidocs.net PDF, page : 146

...
>>>

sum . .

defsum(self):
result=self.first+self.second
returnresult

self result. a.sum() sum


a . sum
self a .

result=self.first+self.second

result=a.first+a.second

a.setdata(4, 2)

a.first=4
a.second=2

result=4+2

wikidocs.net PDF, page : 147

>>>printa.sum()

6 .

80% .
.
, , .

>>>classFourCal:
...defsetdata(self,first,second):
...self.first=first
...self.second=second
...defsum(self):
...result=self.first+self.second
...returnresult
...defmul(self):
...result=self.first*self.second
...returnresult
...defsub(self):
...result=self.first-self.second
...returnresult
...defdiv(self):
...result=self.first/self.second
...returnresult
...
>>>

mul, sub, div sum .


.

>>>a=FourCal()
>>>a.setdata(4,2)
>>>a.sum()
6
>>>a.mul()
8
>>>a.sub()
2

wikidocs.net PDF, page : 148

>>>a.div()
2


.
. .
.

HousePark . pey .

>>>pey=HousePark()

pey.lastname " .

>>>printpey.lastname

pey.fullname .

>>>pey.setname("")
>>>printpey.fullname

travel travel
.

>>>pey.travel(")
,.

wikidocs.net PDF, page : 149

. .
.

>>>classHousePark:
...pass
...
>>>

pey = HousePark() .
pey.lastname "" .

>>>classHousePark:
...lastname=""
...
>>>

lastname . lastname HousePark


lastname " . .

>>>pey=HousePark()
>>>pes=HousePark()
>>>printpey.lastname

>>>printpes.lastname

HousePark lastname ""


.

-
>>> print HousePark.lastname

print pey.fullname .

wikidocs.net PDF, page : 150

>>>classHousePark:
...lastname=""
...defsetname(self,name):
...self.fullname=self.lastname+name
...
>>>

setname .

>>>pey=HousePark()
>>>pey.setname(")

setname "" self.fullname +


.

self.fullname=self.lastname+name

name .

self.fullname=self.lastname+

self setname pey


.

pey.fullname=pey.lastname+"

pey.lastname " .

wikidocs.net PDF, page : 151

pey.fullname="+

pey.setname() .

>>>printpey.fullname

.
travel HousePark .

>>>classHousePark:
...lastname=""
...defsetname(self,name):
...self.fullname=self.lastname+name
...deftravel(self,where):
...print"%s,%s.%(self.fullname,where)
...
>>>

travel . where .
.

>>>pey=HousePark()
>>>pey.setname(")
>>>pey.travel()
,.

travel . travel self


where .

self:pey
where:

wikidocs.net PDF, page : 152

self.fullname pey.fullname pey.fullname pey.setname()


. pey.travel()
.


HousePark
setname .

>>>pey=HousePark()
>>>pey.travel()

. travel self.fullname
self.fullname setname setname
.
. pey
setname .
__init__ .

__init__ , .
.

>>>classHousePark:
...lastname=""
...def__init__(self,name):
...self.fullname=self.lastname+name
...deftravel(self,where):
...print"%s,%s."%(self.fullname,where)
...
>>>

setname __init__ .

. .

wikidocs.net PDF, page : 153

>>>pey=HousePark()
TypeError:__init__()takesexactly2arguments(1given)

.
1 . 1 pey . !
. pey = HousePark() __init__
. __init__(self, name) __init__ .
__init__ ?

>>>pey=HousePark(")

setname .
" . __init__
.

>>>pey=HousePark(")
>>>printpey.travel()
,.

__del__ , .
.
.

>>>pey=HousePark(")
>>>delpey

del pey .
.

wikidocs.net PDF, page : 154

del
.

>>>classHousePark:
...lastname=""
...def__init__(self,name):
...self.fullname=self.lastname+name
...deftravel(self,where):
...print"%s,%s."%(self.fullname,where)
...def__del__(self):
...print"%s%self.fullname
...
>>>

>>>pey=HousePark(")
>>>delpey

__del__
.

(Inheritance)
. .
.
. HousePark
HouseKim .
. HousePark . HouseKim
HousePark .

>>>classHouseKim(HousePark):
...lastname="
...
>>>

" . .

wikidocs.net PDF, page : 155

HouseKim

classHouseKim(HousePark):

>>>classHouseKim:
...lastname=""
...def__init__(self,name):
...self.fullname=self.lastname+name
...deftravel(self,where):
...print"%s,%s."%(self.fullname,where)
...def__del__(self):
...print"%s%self.fullname
...
>>>

, HousePark .

HouseKim .

>>>classHouseKim(HousePark):
...lastname="
...
>>>

>>>julliet=HouseKim("")
>>>julliet.travel(")
,.

HousePark . ?
, .

wikidocs.net PDF, page : 156


. ?
travel
.

>>>julliet=HouseKim(")
>>>julliet.travel(",3)
,3.

HouseKim .

>>>classHouseKim(HousePark):
...lastname=""
...deftravel(self,where,day):
...print"%s,%s%d."%(self.fullname,where,day)
...
>>>

travel travel HouseKim


. .


(+, -, *, /, , , )
. .

>>>pey=HousePark("")
>>>julliet=HouseKim(")
>>>pey+julliet
,

, .

wikidocs.net PDF, page : 157

#house.py
classHousePark:
lastname=""
def__init__(self,name):
self.fullname=self.lastname+name
deftravel(self,where):
print"%s,%s."%(self.fullname,where)
deflove(self,other):
print"%s,%s"%(self.fullname,other.fullname)
def__add__(self,other):
print"%s,%s"%(self.fullname,other.fullname)
def__del__(self):
print"%s"%self.fullname

classHouseKim(HousePark):
lastname=""
deftravel(self,where,day):
print"%s,%s%d."%(self.fullname,where,day)
pey=HousePark("")
julliet=HouseKim("")
pey.love(julliet)
pey+julliet

,
,

pey=HousePark("")
julliet=HouseKim("")
pey.love(julliet)
pey+julliet

wikidocs.net PDF, page : 158

pey = HousePark() pey julliet


. pey.love(julliet) love .

love

deflove(self,other):
print"%s,%s"%(self.fullname,other.fullname)

. pey.love(julliet)
self pey other julliet . ",
.

! .

pey+julliet

'+' . '+'
__add__ .

HousePark .

def__add__(self,other):
print"%s,%s"%(self.fullname,other.fullname)

pey + julliet __add__(self, other) self pey other julliet


. ", .

__del__
, .

, . .


3 .
.

wikidocs.net PDF, page : 159

pey=HousePark(")
julliet=HouseKim(")
pey.travel(")
julliet.travel(",3)
pey.love(julliet)
pey+julliet
pey.fight(julliet)
pey-julliet

.
3 .
,
,
,
,

fight pey - julliet __sub__


'-' .

, .

classHousePark:
lastname=""
def__init__(self,name):
self.fullname=self.lastname+name
deftravel(self,where):
print"%s,%s."%(self.fullname,where)
deflove(self,other):

wikidocs.net PDF, page : 160

print"%s,%s"%(self.fullname,other.fullname)
deffight(self,other):
print"%s,%s"%(self.fullname,other.fullname)
def__add__(self,other):
print"%s,%s"%(self.fullname,other.fullname)
def__sub__(self,other):
print"%s,%s"%(self.fullname,other.fullname)
def__del__(self):
print"%s"%self.fullname

classHouseKim(HousePark):
lastname=""
deftravel(self,where,day):
print"%s,%s%d."%(self.fullname,where,day)

pey=HousePark("")
julliet=HouseKim("")
pey.travel("")
julliet.travel("",3)
pey.love(julliet)
pey+julliet
pey.fight(julliet)
pey-julliet

, .
, 3 .
,
,
,
,

.
.

wikidocs.net PDF, page : 161

[] ?

__init__
__del__

(Constructor),


(Destructor)

(X, Y )

__add__
__or__
__repr__

"+"
"|"
print

X + Y
X | Y
print X

__call__
__getattr__
__getitem__
__setitem__
__getslice__

X()

X.
X[i]
X[key] = value
X[i:j]

__cmp__

X > Y

. .
.
. .

wikidocs.net PDF, page : 162

2)
, .
.

.

.
.

#mod1.py
defsum(a,b):
returna+b

sum mod1py . MS
mod1.py .
mod1.py .
mod1.py . import
. .

mod1.py ? import
.

import

mod1.py ".py" mod1 .

>>>importmod1
>>>printmod1.sum(3,4)
7

mod1.py import mod1 . import mod1.py


. import

wikidocs.net PDF, page : 163

. mod1.py sum mod1.sum


'.'( ) .

mod1.py .

defsafe_sum(a,b):
iftype(a)!=type(b):
print"."
return
else:
result=sum(a,b)
returnresult

.
return
None .

mod1.py .

>>>importmod1
>>>printmod1.safe_sum(3,4)
7

import mod1 mod1.py . mod1.safe_sum(3, 4) safe_num .

>>>printmod1.safe_sum(1,'a')
.
None
>>>

return
None .

sum .

wikidocs.net PDF, page : 164

>>>printmod1.sum(10,20)
30

mod1.sum, mod1.safe_sum sum, safe_sum


. from import .

fromimport

>>>frommod1importsum
>>>sum(3,4)
7

from ~ import ~
. mod1.py sum . sum
safe_sum ? .

frommod1importsum,safe_sum

from import 1, 2
. .

frommod1import*

* . '*'
. from mod1 import * mod1.py
. mod1.py 2
.

if__name__ == "__main__":
mod1.py .

wikidocs.net PDF, page : 165

#mod1.py
defsum(a,b):
returna+b
defsafe_sum(a,b):
iftype(a)!=type(b):
print"."
return
else:
result=sum(a,b)
returnresult

printsafe_sum('a',1)
printsafe_sum(1,4)
printsum(10,10.4)

mod1.py C:\Python
.

C:\Python> python mod1.py


.
None
5
20.4

. mod1.py import
.

C:\WINDOWS> cd \Python
C:\Python> python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import mod1
.
None
5
20.4

wikidocs.net PDF, page : 166


. mod1.py sum safe_sum
import mod1 mod1.py .
.

mod1.py .

if__name__=="__main__":
printsafe_sum('a',1)
printsafe_sum(1,4)
printsum(10,10.4)

C:\Python> python mod1.py __name__ ==


"__main__" if
__name__ == "__main__" if
.

.
.

>>>importmod1
>>>


.
.

#mod2.py
PI=3.141592
classMath:
defsolv(self,r):
returnPI*(r**2)

wikidocs.net PDF, page : 167

defsum(a,b):
returna+b
if__name__=="__main__":
printPI
a=Math()
printa.solv(2)
printsum(PI,4.4)

, . mod2.py C:\Python
.

C:\Python> python mod2.py


3.141592
12.566368
7.541592

C:\Python>python
Python2.1(#15,Apr162001,18:25:49)[MSC32bit(Intel)]onwin32
Type"copyright","credits"or"license"formoreinformation.
>>>importmod2
>>>

__name__ == "__main__" .

>>>printmod2.PI
3.141592

mod2.PI mod2.py PI .

wikidocs.net PDF, page : 168

>>>a=mod2.Math()
>>>printa.solv(2)
12.566368

mod2.py Math .
'.'()
.

>>>printmod2.sum(mod2.PI,4.4)
7.541592

mod2.py sum .




. mod2.py
. ! .

#modtest.py
importmod2
result=mod2.sum(3,4)
printresult

import mod2 mod2


. modtest.py mod2.py
.



. .
C:\Python\Mymodules
.

wikidocs.net PDF, page : 169

mod2.py C:\Python\Mymodules
.

sys .

>>>importsys

sys . sys 3
. sys
.

>>>sys.path
>>>sys.path
['','c:\\','c:\\python21\\dlls','c:\\python21\\lib','c:\\python21\\lib\\plat-win',
'c:\\python21\\lib\\lib-tk','c:\\python21']

sys.path .
.
sys.path C:\Python\Mymodues ?

sys.path .

>>>sys.path.append("C:\Python\Mymodules")
>>>sys.path
['','c:\\','c:\\python21\\dlls','c:\\python21\\lib','c:\\python21\\lib\\plat
-win','c:\\python21\\lib\\lib-tk','c:\\python21','C:\\Python\\Mymodules']
>>>

sys.path.append C:\Python\Mymodules sys.path


sys.path C:\\Python\\Mymodules
.

wikidocs.net PDF, page : 170

>>>importmod2
>>>printmod2.sum(3,4)
7

.
sys.path.append() .

reload
reload (import)
. .
reload .
.

>>>importmod2
>>>printmod2.PI
3.141592

mod2.py PI .

PI=3.14

PI (3.14) .
.

>>>reload(mod2)
>>>printmod2.PI
3.14

. reload import
? . reload
import .
mod2.py import
mod2 .

wikidocs.net PDF, page : 171

3)
(try, except)
.
. ,
. try, except
.
.

?
.
.
.

>>>f=open('','r')
Traceback(mostrecentcalllast):
File"",line1,in?
IOError:[Errno2]Nosuchfileordirectory:'\xb3\xaa\xbe\xf8\xb4\xc2\xc6\xc4\xc0\xcf'

IOError .
'' .
.

'\xb3\xaa\xbe\xf8\xb4\xc2\xc6\xc4\xc0\xcf'

0 .

>>>4/0
Traceback(mostrecentcalllast):
File"",line1,in?
ZeroDivisionError:integerdivisionormodulobyzero
>>>

4 0 ZeroDivisionError .

. .

wikidocs.net PDF, page : 172

>>>a=[1,2,3]
>>>a[4]
Traceback(mostrecentcalllast):
File"",line1,in?
IndexError:listindexoutofrange
>>>

a [1, 2, 3] a[4] a IndexError


. .


, .
try, except .

try:
...
except[[,]]:
...

try except .
try except .

except .

except [ [, ]]:

[ [, ]] .
try, except

try:
...
except:
...

wikidocs.net PDF, page : 173

except

try
...
except:
...

except .

try
...
except,:
...


except except
except
.

try:
4/0
exceptZeroDivisionError,e:
printe

4 0 ZeroDivisioError except
except e .

: integer division or modulo by zero

wikidocs.net PDF, page : 174


.

. ?

>>>try:
...f=open(".txt",'r')
...exceptIOError:
...print"."
...f=open(".txt",'w')
...
.

try try f = open(".txt, 'r')


IOError . except
. except
except . , "
.txt .
.
try, except
.

(raise)
. raise
. Bird
fly ( ) .

classBird:
deffly(self):
raiseNotImplementedError

Bird fly fly


.

wikidocs.net PDF, page : 175


Bird fly .

classEagle(Bird):
deffly(self):
return"veryfast"

wikidocs.net PDF, page : 176

4)
.
. .
.

.
.
,
.
.
.
.

wikidocs.net PDF, page : 177

[1]
. print, del, type .
import .
.
.
.
.

abs
abs(x) , .

>>>abs(3)
3
>>>abs(-3)
3
>>>abs(1+2j)
2.2360679774997898
>>>

abs(a + bj) = sqrt (a^2+b^2)

apply
apply(function, (args))
.

>>>defsum(a,b):
...returna+b
>>>

wikidocs.net PDF, page : 178

apply
.

>>>apply(sum,(3,4))
7

chr
chr(i) .

>>>chr(97)
'a'
>>>chr(48)
'0'
>>>

cmp
cmp(x,y) . x .
0 .

>>>cmp(4,3)
1
>>>cmp(3,4)
-1
>>>cmp(3,3)
0

dir
dir .
() .
.

wikidocs.net PDF, page : 179

>>>dir([1,2,3])
['append','count','extend','index','insert','pop','remove','reverse','sort']
>>>dir({'1':'a'})
['clear','copy','get','has_key','items','keys','setdefault','update','values']

divmod
divmod(a,b)
.

>>>divmod(7,3)
(2,1)
>>>divmod(1.3,0.2)
(6.0,0.099999999999999978)

enumerate
enumerate (, , ) enumerate
. enumerate ,
.

enumerate for .

>>>fori,nameinenumerate(['boby','foo','bar']):
...printi,name
...
0boby
1foo
2bar


enumerate .

wikidocs.net PDF, page : 180

eval
eval(expression) (1+2, 'hi' + 'a' )
.

>>>eval('1+2')
3
>>>eval("'hi'+'a'")
'hia'
>>>eval('divmod(4,3)')
(1,1)

execfile
execfile(file) . ,
sum.py ,

#sum.py
defsum(a,b):
returna+b
printsum(3,4)

>>>execfile('sum.py')
7

filter
filter(function, list)
, . filter
. filter . .

#positive.py
defpositive(l):
result=[]

wikidocs.net PDF, page : 181

foriinl:
ifi>0:
result.append(i)
returnresult
printpositive([1,-3,2,0,-5,6])

[1, 2, 6]

, positive
.

filter .

#filter1.py
defpositive(x):
returnx>0
printfilter(positive,[1,-3,2,0,-5,6])

[1, 2, 6]

filter ,
(, , ) . filter
. 1,
2, 6 x > 0 [1, 2, 6] .

lambda . (lambda .)

>>>printfilter(lambdax:x>0,[1,-3,2,0,-5,6])
[1,2,6]

wikidocs.net PDF, page : 182


hex
hex(x) (hexadecimal) .

>>>hex(234)
'0xea'
>>>hex(3)
'0x3'

id
id(object) () .

>>>a=3
>>>id(3)
135072304
>>>id(a)
135072304
>>>b=a
>>>id(b)
135072304

a, b 3 .

4 id(4) .

>>>id(4)
135072292

input
input([prompt]) . raw_input " "
.
.

wikidocs.net PDF, page : 183

>>>a=input()
'hi'
>>>a
'hi'
>>>b=input("Enter:")
Enter:'hi'

>>>b
'hi'

int
int(x) .
.

>>>int('3')
3
>>>int(3.4)
3

int(x, radix) x radix() .

'11' .

>>>int('11',2)
3

'1A' .

>>>int('1A',16)
26

wikidocs.net PDF, page : 184

isinstance
isinstance(object, class)
True, False .

>>>classPerson:pass
...
>>>a=Person()
>>>b=3
>>>isinstance(a,Person)
True

a Person .

>>>isinstance(b,Person)
False

b Person .

lambda
lambda def
. lambda def def
. lambda .

lambda 1, 2,,, :

>>>sum=lambdaa,b:a+b
>>>sum(3,4)
7

wikidocs.net PDF, page : 185

lambda sum a, b a b . lambda


sum def .

>>>defsum(a,b):
...returna+b
...
>>>

def lambda ? . lambda def


def lambda .
lambda .

>>>l=[lambdaa,b:a+b,lambdaa,b:a*b]
>>>l
[at0x811eb2c>,at0x811eb64>]

lambda . l[0]
lambda .

>>>l[0]
at0x811eb2c>
>>>l[0](3,4)
7

l[1] lambda .

>>>l[1](3,4)
12

lambda .

len
len(s) (, , ) ( )
.

wikidocs.net PDF, page : 186

>>>len("python")
6
>>>len([1,2,3])
3
>>>len((1,'a'))
2

list
list(s)
. .

>>>list("python")
['p','y','t','h','o','n']
>>>list((1,2,3))
[1,2,3]
>>>a=[1,2,3]
>>>b=list(a)
>>>b
[1,2,3]
>>>id(a)
9164780
>>>id(b)
9220284

List(a) . a b
id .

long
long(x) (long integer)
.

>>>long('34567890')
34567890L
>>>long(34567890)
34567890L

wikidocs.net PDF, page : 187

map
map (, , )
.

deftwo_times(l):
result=[]
foriinl:
result.append(i*2)
returnresult

2 .

#two_times.py
deftwo_times(l):
result=[]
foriinl:
result.append(i*2)
returnresult
result=two_times([1,2,3,4])
printresult

[2, 4, 6, 8]

wikidocs.net PDF, page : 188

>>>deftwo_times(x):returnx*2
...
>>>map(two_times,[1,2,3,4])
[2,4,6,8]

map
. . 1 two_times
1 * 2 2 [] . [2] ,
2 two_times 4
[2] [2, 4] . 4 [2, 4, 6,
8] [2, 4, 6, 8] . map
. map .

lambda .

>>>map(lambdaa:a*2,[1,2,3,4])
[2,4,6,8]

[map 1 ]

#map_test.py
defplus_one(x):
returnx+1
printmap(plus_one,[1,2,3,4,5])

: [2,3,4,5,6]

max
max(s) (, , ) .

>>>max([1,2,3])
3
>>>max("python")
'y'

wikidocs.net PDF, page : 189


min
min(s) max .

>>>min([1,2,3])
1
>>>min("python")
'h'

oct
oct(x) 8 .

>>>oct(34)
'042'
>>>oct(12345)
'030071'

open
open(filename, [mode]) .
(mode) ('r') .
.
mode
w
r
a
b

w+, r+, a+ .

b w, r, a .

>>>f=open("binary_file","rb")
>>>fwrite=open("write_mode.txt",'w')
>>>fread=open("read_mode.txt",'r')

wikidocs.net PDF, page : 190

>>>fread2=open("read_mode.txt")

fread fread2 . , 'r' .

>>>fappend=open("append_mode.txt",'a')

ord
ord(c) .

>>>ord('a')
97
>>>ord('0')
48

pow
pow(x, y) x y .

>>>pow(2,4)
16
>>>pow(3,3)
27

range
range([start,] stop [,step]) for
.

wikidocs.net PDF, page : 191

>>>range(5)
[0,1,2,3,4]

( .
. )

>>>range(5,10)
[5,6,7,8,9]

- .

>>>range(1,10,2)
[1,3,5,7,9]
>>>range(0,-10,-1)
[0,-1,-2,-3,-4,-5,-6,-7,-8,-9]

raw_input
raw_input([prompt]) prompt .
('\n') .

>>>a=raw_input()
youneedpython
>>>a
'youneedpython'
>>>b=raw_input("--->")
--->youneedpython
>>>b
'youneedpython'

input raw_input .

wikidocs.net PDF, page : 192

reduce
reduce(function, sequence) function

.

#reduce1.py
deftest(x,y):
returnx+y
deftest2(x,y):
returnx*y
printreduce(test,[1,2,3,4,5])
printreduce(test2,[1,2,3,4,5])

15
120

reduce(test, [1,2,3,4,5]) .

((((1+2)+3)+4)+5)

reduce(test2, [1,2,3,4,5]) .

((((1*2)*3)*4)*5)

reload
reload(module) (import) .
.

wikidocs.net PDF, page : 193

#test.py
defa():
print"lifeistooshort"

>>>importtest
>>>test.a()
'lifeistooshort'

test.py .

#test.py
defa():
print"youneedpython"

>>>test.a()
'lifeistooshort'
>>>reload(test)
>>>test.a()
'youneedpython'

,
.

repr
repr(object) .
eval . str str eval
.

wikidocs.net PDF, page : 194

>>>repr("hi".upper())
"'HI'"
>>>eval(repr("hi".upper()))
'HI'
>>>eval(str("hi".upper()))
Traceback(innermostlast):
File"",line1,in?eval(str("hi".upper()))
File"",line0,in?
NameError:Thereisnovariablenamed'HI'

str eval .

sorted
sorted .

>>>sorted([3,1,2])
[1,2,3]
>>>sorted(['a','c','b'])
['a','b','c']
>>>sorted("zero")
['e','o','r','z']
>>>sorted((3,2,1))
[1,2,3]

sort . sort
.
sorted sort .

>>>a=[3,1,2]
>>>result=a.sort()
>>>printresult
None
>>>a
[1,2,3]

wikidocs.net PDF, page : 195

str
str(object) .
. repr .

>>>str(3)
'3'
>>>str('hi')
'hi'
>>>str('hi'.upper())
'HI'

tuple
tuple(sequence) .
.

>>>tuple("abc")
('a','b','c')
>>>tuple([1,2,3])
(1,2,3)
>>>tuple((1,2,3))
(1,2,3)

type
type(object) .

>>>type("abc")
>>>type([])
>>>type(open("test",'w'))

'file' .

zip
zip .
.

wikidocs.net PDF, page : 196

>>>zip([1,2,3],[4,5,6])
[(1,4),(2,5),(3,6)]
>>>zip([1,2,3],[4,5,6],[7,8,9])
[(1,4,7),(2,5,8),(3,6,9)]
>>>zip("abc","def")
[('a','d'),('b','e'),('c','f')]

wikidocs.net PDF, page : 197

[2]

.
. . , .
.
.
.
. ,
.
.
.
( .)

(sys.argv)
sys
.

sys.argv

C:\Python21> python test.py abc pey guido

python test.py sys.argv


.

)
1. . (C:\Python\Mymoduels
.)

#argv_test.py
importsys
printsys.argv

2. .

wikidocs.net PDF, page : 198

C:\Python\Mymodules> python argv_test.py you need python


['argv_test.py', 'you', 'need', 'python']

python sys.argv
. 2 .

(sys.exit)

>>> sys.exit()

sys.exit Ctrl-Z Crtl-D . ,


.

(sys.path)
sys.path . , xxx.py
.

>>>importsys
>>>sys.path
['','c:\python21','c:\python21\dlls','c:\python21\lib','c:\python21\l
ib\plat-win','c:\python21\lib\lib-tk']
>>>

'' .

#path_append.py
importsys
sys.path.append("C:\Python\Mymodules")

sys.path.append .
C:\Python\Mymodules xxx.py .

wikidocs.net PDF, page : 199

(pickle)
pickle
.

data pickle.dump
.

>>>importpickle
>>>f=open("test.txt",'w')
>>>data={1:'python',2:'youneed'}
>>>pickle.dump(data,f)
>>>f.close()

pickle.dump (data)
.

>>>importpickle
>>>f=open("test.txt",'r')
>>>data=pickle.load(f)
>>>printdata
{2:'youneed',1:'python'}

(string)
string . 2
. string
. string .

>>>importstring
>>>dir(string)
['_StringType','__builtins__','__doc__','__file__','__name__','_float','_idmap','_idmapL','_int',
'_long','atof','atof_error','atoi','atoi_error','atol','atol_error','capitalize','capwords',

wikidocs.net PDF, page : 200

'center','count','digits','expandtabs','find','hexdigits','index','index_error','join','joinfield
'letters','ljust','lower','lowercase','lstrip','maketrans','octdigits','printable','punctuation',
'replace','rfind','rindex','rjust','rstrip','split','splitfields','strip','swapcase','translate',
'upper','uppercase','whitespace','zfill']

dir(string)
. , .

>>>importstring
>>>string.split("youneedpython")
['you','need','python']
>>>"youneedpython".split()
['you','need','python']

string split split


. string .

atof
.

>>>string.atof('3')
3.0

atof . .

>>>float('3')
3

atoi
atof . int
.

wikidocs.net PDF, page : 201

>>>string.atoi('3')
3
>>>int('3')
3

zfill
0 . zfill zero +
fill 0 .

>>>string.zfill(3,8)
'00000003'
>>>string.zfill('a',3)
'00a'

string.zfill(a, b) (a) (b) .


2001-04-04 04 04 0 .
zfill .

(StringIO)
StringIO . .

[]
StringIO (import).

>>>importStringIO

StringIO StringIO StringIO .


. .

>>>f=StringIO.StringIO()

wikidocs.net PDF, page : 202

write "life is too short" .

>>>f.write("lifeistooshort")

getvalue value .
getvalue StringIO .

>>>value=f.getvalue()
>>>value
'lifeistooshort'

close .

>>>f.close()

[] StringIO


.
.
StringIO.
StringIO .

? (os.environ)

os environ. .

>>>importos
>>>os.environ
{'CMDLINE':'WIN','PATH':'C:\WINDOWS;C:\WINDOWS\COMMAND;C:\PROGRA~1\ULTRA
EDT;C:\JDK1.3\BIN;C:\ESSOLO.COM;C:\VIM\VIM\VIM57;C:\PYTHON21','BLASTER':

wikidocs.net PDF, page : 203

'A240I10D1','TEMP':'C:\WINDOWS\TEMP','COMSPEC':'C:\WINDOWS\COMMAND.CO
M','PROMPT':'$p$g','WINBOOTDIR':'C:\WINDOWS','WINDIR':'C:\WINDOWS','TMP
':'C:\WINDOWS\TEMP'}
>>>

. os.environ .
.

. PATH.
C:\WINDOWS\autoexec.bat .

>>>os.environ['PATH']
'C:\WINDOWS;C:\WINDOWS\COMMAND;C:\PROGRA~1\ULTRAEDT;C:\JDK1.3\BIN;C:\ESS
OLO.COM;C:\VIM\VIM\VIM57;C:\PYTHON21'
>>>

(os.chdir, os.getcwd)
.

>>>os.chdir("C:\WINDOWS")
os.getcwd()

>>>os.getcwd()
'C:\WINDOWS'

(os.system, os.popen)
os.system
. os.system()
. dir .

wikidocs.net PDF, page : 204

>>>os.system("dir")

dir

os.popen
os.popen .

>>>files=os.popen("dir")
>>>files
>>>

>>>printfiles.read()

os

os.mkdir()

os.rmdir()

.,
.

os.unlink()

os.rename(src, dst)

src dst
.

(shutil)
shutil .

shutil.copy(src, dst)
src dst . dst src

wikidocs.net PDF, page : 205

dst .

>>>importshutil
>>>shutil.copy("src","dst")

(glob)

glob.

glob(pathname)
glob . *, ?
.

C:\Python Q
.

>>>importglob
>>>glob.glob("C:\Python\Q*")
['C:\Python\quiz.py','C:\Python\quiz.py.bak']
>>>

(tempfile)
tempfile. tempfile.mktemp()
.

>>>importtempfile
>>>filename=tempfile.mktemp()
>>>filename
'C:\WINDOWS\TEMP\~-275151-0'

tempfile.TemporaryFile() . w+b
. f.close() .

wikidocs.net PDF, page : 206

>>>importtempfile
>>>f=tempfile.TemporaryFile()

(time)
time . .

time.time
time.time() UTC(Universal Time Coordinated )
. 1970 1 1 0 0 0
.

>>>importtime
>>>time.time()
988458015.73417199

time.localtime
time.localtime time.time() , , , , , ,..
.

>>>time.localtime(time.time())
(2001,4,28,20,48,12,5,118,0)

time.asctime
time.localtime
. .

>>>time.asctime(time.localtime(time.time()))
'SatApr2820:50:202001'

wikidocs.net PDF, page : 207


time.ctime
time.asctime .

>>>time.ctime()
'SatApr2820:56:312001'

time.strftime
time.strftime(' ', time.localtime(time.time())) strftime
.

%a

Mon

%A

Monday

%b

Jan

%B

January

%c

(
)

06/01/01 17:22:21

%d

(day)

[00,31]

%H

(hour)-24

[00,23]

%I

(hour)-12

[01,12]

%j

[001,366]

%m

[01,12]

%M

[01,59]

%p

AM or PM

AM

%S

[00,61]

%U

1 -

[00,53]

%w

[0(),6]

wikidocs.net PDF, page : 208

%W

1 -

[00,53]

%x

06/01/01

%X

17:22:21

%Y

2001

%Z

%%

%y

01

>>>importtime
>>>time.strftime('%x',time.localtime(time.time()))
'05/01/01'
>>>time.strftime('%c',time.localtime(time.time()))
'05/01/0117:22:21'

time.sleep
time.sleep
. .

#sleep1.py
importtime
foriinrange(10):
printi
time.sleep(1)

1 0 9 . time.sleep
. 1 1 0.5 0.5 .

wikidocs.net PDF, page : 209

(calendar)
.

2001 .

>>>importcalendar
>>>printcalendar.calendar(2001)

>>>calendar.prcal(2001)

2001 4 . .
.

>>>calendar.prmonth(2001,4)
April2001
MoTuWeThFrSaSu
1
2345678
9101112131415
16171819202122
23242526272829
30

calendar . weekday(, , )
. 0, 1, 2, 3, 4,
5, 6 .

>>>calendar.weekday(2001,4,28)
5

2001 4 28 .monthrange(, )
1 .

wikidocs.net PDF, page : 210

>>>calendar.monthrange(2001,4)
(6,30)

2001 4 1 30 .
.

(random)
random . random randint .

0.0 1.0 .

>>>importrandom
>>>random.random()
0.53840103305098674

1 10 .

>>>random.randint(1,10)
6

1 55 .

>>>random.randint(1,55)
43

#random_pop.py
importrandom
defrandom_pop(data):
number=random.randint(0,len(data)-1)

wikidocs.net PDF, page : 211

returndata.pop(number)
if__name__=="__main__":
data=[1,2,3,4,5]
whiledata:printrandom_pop(data)

2
3
1
5
4

random_pop
. .

(thread)
(Process) .
,
. .

#thread_test.py
importthread
importtime
defsay(msg):
while1:
printmsg
time.sleep(1)
thread.start_new_thread(say,('you',))
thread.start_new_thread(say,('need',))
thread.start_new_thread(say,('python',))
foriinrange(100):
printi
time.sleep(0.1)

. 1 'you', 'need', 'python'


. 0.1 0 99 . for

wikidocs.net PDF, page : 212

Main .

0
you
need
python
1
2
3
4
5
6
7
8
9
10
you
need
python
11
12
...

thread.start_new_thread ,
. apply
.

(webbrowser)
webbrowser .

URL http://www.yahoo.co.kr .

>>>importwebbrowser
>>>webbrowser.open(http://www.yahoo.co.kr)

wikidocs.net PDF, page : 213

webbrowser open
.

open_new .

>>>webbrowser.open_new(http://www.yahoo.co.kr)

wikidocs.net PDF, page : 214

06. ?
.
.

.
.
.

.

wikidocs.net PDF, page : 215

[01] ?
.

, ,
?


.
.
. 5
. .
,
.
.
.
.

. .
. 2 2
.
. .
. .

. , GuGu 2 result
.

result=GuGu(2)

. 2 2,4,6,,,18 .
. result = [2, 4, 6, 8, 10, 12, 14, 16,
18] .
. .

defGuGu(n):
printn

wikidocs.net PDF, page : 216

GuGu(2) 2 . 2
.

defGuGu(n):
result=[]

result 2, 4, 6,,, 18 .
.

defGuGu(n):
result=[]
result.append(n*1)
result.append(n*2)
result.append(n*3)
...
result.append(n*9)
returnresult

2 .
. 1 9 ?
1 9 .

>>>i=1
>>>whilei<10:
...printi
...i=i+1

. GuGu .

wikidocs.net PDF, page : 217

defGuGu(n):
result=[]
i=1
whilei<10:
result.append(n*i)
i=i+1
returnresult

printGuGu(2)

.

.
,
. .
.
. , 4
.

wikidocs.net PDF, page : 218

[02]
.

#memo.py
importsys
importtime
defusage():
print"""
Usage
=====
%s-v:Viewmemo
%s-a:Addmemo
"""%(sys.argv[0],sys.argv[0])
ifnotsys.argv[1:]orsys.argv[1]notin['-v','-a']:
usage()
elifsys.argv[1]=='-v':
try:printopen("memo.txt").read()
exceptIOError:print"memodoesnotexist!"
elifsys.argv[1]=='-a':
word=raw_input("Entermemo:")
f=open("memo.txt",'a')
f.write(time.ctime()+':'+word+'\n')
f.close()
print"Added"

python memo.py -v
"memo does not exist!" . python memo.py -a
memo.txt .
python memo.py -v python memo.py -a
usage() . sys.argv try.. except
.

wikidocs.net PDF, page : 219

[03] tab 4 space


(Tab) (4 Space)
. VI
. 8
. .

#tabto4.py
importre
importsys
defusage():
print"Usage:python%sfilename"%sys.argv[0]
try:f=open(sys.argv[1])
except:usage();sys.exit(2)
msg=f.read()
f.close()
p=re.compile(r'\t')
changed=p.sub(""*4,msg)
f=open(sys.argv[1],'w')
f.write(changed)
f.close()

re . p
= re.compile(r'\t') . r'\t' \t .
r raw . .

p=re.compile('\\t')

p sub " "*4 ,


. sub .

p.sub(""*4,msg)

wikidocs.net PDF, page : 220

[04] 12345 12,345


123,456
.

#commanumber.py
importstring
defcomma_number(number):
ifnumber[0]in['+','-']:
sign_mark,number=number[:1],number[1:]
else:
sign_mark=''
try:
tmp=string.split(number,'.')
num=tmp[0];decimal='.'+tmp[1]
except:
num=number;decimal=''
head_num=len(num)%3
result=''
forposinrange(len(num)):
ifpos==head_numandhead_num:
result=result+','
elif(pos-head_num)%3==0andpos:
result=result+','
result=result+num[pos]
returnsign_mark+result+decimal
printcomma_number("12345678.345678")

12,345,678.345678

'+', '-' sign_mark .


'.' ','
decimal .

head_num=len(num)%3

wikidocs.net PDF, page : 221


'.' 3 .

forposinrange(len(num)):
ifpos==head_numandhead_num:
result=result+','
elif(pos-head_num)%3==0andpos:
result=result+','
result=result+num[pos]

.
','
(num)
3
3 ',' .
.

3
.
for head_num,
head_num 0 ',' .
.

.
.
. Simple ?

.
?
(at 2008.02 by )

importunittest
defcomma_number(no):
t=no.split(".")
decimal=t[0]
sosu=""
iflen(t)>1:sosu=t[1]
ifsosu:
returncomma(decimal)+"."+sosu
else:
returncomma(decimal)
defcomma(no):
result=[]
numbers=list(str(no))

wikidocs.net PDF, page : 222

numbers.reverse()
fori,ninenumerate(numbers):
ifi%3==0andi:result.insert(0,",")
result.insert(0,n)
return"".join(result)
classCommaTest(unittest.TestCase):
deftest1(self):
self.assertEquals("",comma_number(""))
self.assertEquals("1",comma_number("1"))
self.assertEquals("12",comma_number("12"))
self.assertEquals("123",comma_number("123"))
self.assertEquals("1,234",comma_number("1234"))
self.assertEquals("1,234.02",comma_number("1234.02"))
self.assertEquals("3,312,345.3234",comma_number("3312345.3234"))
if__name__=="__main__":
unittest.main()

wikidocs.net PDF, page : 223

[05]
PC
.( .)

.

importos
defsearch(dirname):
flist=os.listdir(dirname)
forfinflist:
next=os.path.join(dirname,f)
ifos.path.isdir(next):
search(next)
else:
doFileWork(next)

defdoFileWork(filename):
ext=os.path.splitext(filename)[-1]
ifext=='.py':printfilename

search("d:/")


. search
doFileWork .

d .py .
.py "ABC" "DEF" doFileWork
.

defdoFileWork(filename):
ext=os.path.splitext(filename)[-1]
ifext!=".py":return
f=open(filename)

wikidocs.net PDF, page : 224

before=f.read()
f.close()
after=before.replace("ABC","DEF")
f=open(filename,"w")
f.write(after)
f.close()

wikidocs.net PDF, page : 225

[06] ?
"2007 1 1" "" .
.

1 2

1 48

UI . .

importdatetime
defelapsed_time(sdate):
e=datetime.datetime.now()
ifnotsdateorlen(sdate)<14:return0,0,0,0
s=datetime.datetime(int(sdate[:4]),int(sdate[4:6]),int(sdate[6:8]),
int(sdate[8:10]),int(sdate[10:12]),int(sdate[12:14]))
days=(e-s).days
sec=(e-s).seconds
hour,sec=divmod(sec,3600)
minute,sec=divmod(sec,60)
returndays,hour,minute,sec

, , ,
.
datetime"-".

(datetime.datetime.now()-datetime.timedelta(7)).strftime("%Y%m%d")

wikidocs.net PDF, page : 226

datetime now() timedelta() 1 datetime


YYYYMMDD .

datetime
.

wikidocs.net PDF, page : 227

07.
.
.
.
TDD(Test Driven Development) .

wikidocs.net PDF, page : 228

[1] ?
, , IT
.
.
,
.
, .

TDD?
.
IT
" . "TDD"
. TDD Test Driven Development
" " .
.
TDD ", ?
! !". !
TDD .

",
!"
TDD
"" . TDD " "
, .

TDD
. TDD
.
.
.
TDD ,
.

.

wikidocs.net PDF, page : 229


. ( )

TDD
TDD , . .

1. .
2. .
3. .
4. . ( )
5. .

TDD
Simple Code TDD . (Kent Beck, ExtremeProgramming .
.), (Ward Cunningham)
(Extreme Programming) (Ron Jeffries) Simple Code
.

Clean code that works! ( !)


Simple Code .
. "~
!" .
. TDD
Simple .

wikidocs.net PDF, page : 230

,
. TDD .

wikidocs.net PDF, page : 231

[2] PyUnit
pyunit
.

importunittest
classSimpleTest(unittest.TestCase):
deftest1(self):
self.assertEquals(1,1)
if__name__=="__main__":
unittest.main()

.
1. pyunit unittest import.
2. unittest.TestCase SimpleTest .
3. (:test1, test
. unittest.main() unittest
test .).
4. self.assertEquals TestCase 1 1
.
5.

1 1 unittest
.
TestCase assertEquals .
.

assertEquals(x,y)

x y

assertTrue(x)

wikidocs.net PDF, page : 232

assertFalse(x)

fail(msg)

, msg

failIf(x)

pyunit TDD .

wikidocs.net PDF, page : 233

[3] SubDate
Sub Date
(YYYYMMDD) . .

20030515 sub 20030501 = 14


20030501 sub 20030515 = 14
20030301 sub 20030515 = 31 + 30 + 14

TDD .

?
.
. 28 29 ,,

= absolute( - )

, 0 .

TODO
.

.
.
.
.

wikidocs.net PDF, page : 234

. 20030515
.

2003 5 15 = 2002 + 2003 1 4


+ 15

TDD Start
TODO
(YYYYMMDD) .
.
.
.
.

TODO TDD . TODO


. .

importunittest
classSubDateTest(unittest.TestCase):
deftestGetDayByYear(self):
subdate=SubDate()
self.assertEquals(0,subdate.getTotalDayByYear(1))
self.assertEquals(365,subdate.getTotalDayByYear(2))

if__name__=="__main__":
unittest.main()

0 1 0 . ( 1 1
1 .) 2 1 1 1 2 1 1
365 .

wikidocs.net PDF, page : 235

classSubDate:
defgetTotalDayByYear(self,year):
ifyear==1:return0
else:return365

self.assertEquals(365*3+366, subdate.getTotalDayByYear(5))

1 4
.
TODO

deftestLeapYear(self):
subdate=SubDate()
self.assertTrue(subdate.isLeapYear(0))
self.assertFalse(subdate.isLeapYear(1))
self.assertTrue(subdate.isLeapYear(4))

classSubDate:
defgetTotalDayByYear(self,year):
ifyear==1:return0
else:return365
defisLeapYear(self,year):
if(year==0):returnTrue
if(year==1):returnFalse

wikidocs.net PDF, page : 236

if(year==4):returnTrue
returnFalse

duplication . 0, 1, 4
. .

defisLeapYear(self,year):
ifyear%4==0:returnTrue
returnFalse

4 4
.

. 4
.
.

400 .
100 .
4 .
.

1200 400 100 400


. 700 100 . 400, 100, 4
.

deftestLeapYear(self):
subdate=SubDate()
self.assertTrue(subdate.isLeapYear(0))
self.assertFalse(subdate.isLeapYear(1))

wikidocs.net PDF, page : 237

self.assertTrue(subdate.isLeapYear(4))
self.assertTrue(subdate.isLeapYear(1200))
self.assertFalse(subdate.isLeapYear(700))

self.assertFalse(subdate.isLeapYear(700)) .

defisLeapYear(self,year):
ifyear%100==0:returnFalse
ifyear%4==0:returnTrue
returnFalse

assertTrue(subdate.isLeapYear(1200)) .
.

defisLeapYear(self,year):
ifyear%400==0:returnTrue
ifyear%100==0:returnFalse
ifyear%4==0:returnTrue
returnFalse

.
? . .
.
. ( . ... )

#self.assertEquals(365*3+366,subdate.getTotalDayByYear(5))

wikidocs.net PDF, page : 238

defgetTotalDayByYear(self,year):
result=0
foriinrange(1,year):
ifself.isLeapYear(i):result+=366
else:result+=365
returnresult

getTotalDayByYear
.

getTotalDayByYear=>getTotalDayLessThanYearOf

, . .

deftestGetDayByMonth(self):
subdate=SubDate()
self.assertEuqlas(0,subdate.getTotalDayLessThanMonthOf(1))
self.assertEquals(31,subdate.getTotalDayLessThanMonthOf(2))

defgetTotalDayLessThanMonthOf(self,month):
ifmonth==1:return0
else:return31

. 2,
? . ,

deftestGetDayByMonth(self):
subdate=SubDate()
self.assertEquals(0,subdate.getTotalDayLessThanMonthOf(1,True))
self.assertEquals(31,subdate.getTotalDayLessThanMonthOf(2,False))

wikidocs.net PDF, page : 239


2 .
.

defgetTotalDayLessThanMonthOf(self,month,isLeap):
ifmonth==1:return0
else:return31

deftestGetDayByMonth(self):
subdate=SubDate()
self.assertEquals(31+28,subdate.getTotalDayLessThanMonthOf(3,False))
self.assertEquals(31+29,subdate.getTotalDayLessThanMonthOf(3,True))

3 .
.

defgetTotalDayLessThanMonthOf(self,month,isLeap):
monthDays=[31,28,31,30,31,30,31,31,30,31,30,31]
result=0
foriinrange(1,month):
ifisLeapandi==1:
result+=monthDays[i-1]+1
else:
result+=monthDays[i-1]
returnresult

monthDays=[31,28,31,30,31,30,31,31,30,31,30,31]
defgetTotalDayLessThanMonthOf(self,month,isLeap):
result=0
foriinrange(1,month):

wikidocs.net PDF, page : 240

result+=self.monthDays[i-1]
ifisLeapandmonth>2:result+=1
returnresult

monthDays global ,
.

.
.

deftestGetTotalDay(self):
subdate=SubDate()
self.assertEquals(1,subdate.getTotalDayOf("00010101"))
self.assertEquals(366,subdate.getTotalDayOf("00020101"))

1 1 1 1 , 2 1 1 366 .

defgetTotalDayOf(self,date):
year=int(date[:4])month=int(date[4:6])
day=int(date[6:])
returnself.getTotalDayLessThanYearOf(year)+\
self.getTotalDayLessThanMonthOf(month,self.isLeapYear(year))+day

.
.

deftestSubDate(self):
subdate=SubDate()
self.assertEquals(1,subdate.getSubDate("20021231","20030101"))
self.assertEquals(31+28+30+31+14,subdate.getSubDate("20030101","20030515"))
self.assertEquals(31+29+30+31+14,subdate.getSubDate("20040101","20040515"))

wikidocs.net PDF, page : 241


20021231 200311 1. ,

defgetSubDate(self,date1,date2):
returnabs(self.getTotalDayOf(date1)-self.getTotalDayOf(date2))

.
Congratulations!!

importunittest
classSubDateTest(unittest.TestCase):
deftestGetDayByYear(self):
subdate=SubDate()
self.assertEquals(0,subdate.getTotalDayLessThanYearOf(1))
self.assertEquals(365,subdate.getTotalDayLessThanYearOf(2))
self.assertEquals(365*3+366,subdate.getTotalDayLessThanYearOf(5))
deftestLeapYear(self):
subdate=SubDate()
self.assertTrue(subdate.isLeapYear(0))
self.assertFalse(subdate.isLeapYear(1))
self.assertTrue(subdate.isLeapYear(4))
self.assertTrue(subdate.isLeapYear(1200))
self.assertFalse(subdate.isLeapYear(700))
deftestGetDayByMonth(self):
subdate=SubDate()
self.assertEquals(31+28,subdate.getTotalDayLessThanMonthOf(3,False))
self.assertEquals(31+29,subdate.getTotalDayLessThanMonthOf(3,True))
deftestGetTotalDay(self):
subdate=SubDate()
self.assertEquals(1,subdate.getTotalDayOf("00010101"))
self.assertEquals(366,subdate.getTotalDayOf("00020101"))
deftestSubDate(self):
subdate=SubDate()
self.assertEquals(1,subdate.getSubDate("20021231","20030101"))

wikidocs.net PDF, page : 242

self.assertEquals(31+28+30+31+14,subdate.getSubDate("20030101","20030515"))
self.assertEquals(31+29+30+31+14,subdate.getSubDate("20040101","20040515"))
if__name__=="__main__":
unittest.main()

classSubDate:
defgetTotalDayLessThanYearOf(self,year):
result=0
foriinrange(1,year):
ifself.isLeapYear(i):result+=366
else:result+=365
returnresult
defisLeapYear(self,year):
ifyear%400==0:returnTrue
ifyear%100==0:returnFalse
ifyear%4==0:returnTrue
returnFalse
monthDays=[31,28,31,30,31,30,31,31,30,31,30,31]
defgetTotalDayLessThanMonthOf(self,month,isLeap):
result=0
foriinrange(1,month):
result+=self.monthDays[i-1]
ifisLeapandmonth>2:result+=1
returnresult
defgetTotalDayOf(self,date):
year=int(date[:4])
month=int(date[4:6])
day=int(date[6:])
returnself.getTotalDayLessThanYearOf(year)+\
self.getTotalDayLessThanMonthOf(month,self.isLeapYear(year))+day
defgetSubDate(self,date1,date2):
returnabs(self.getTotalDayOf(date1)-self.getTotalDayOf(date2))

wikidocs.net PDF, page : 243

[4]
HTTP .
HTTP www(World Wide Web) ,
www.naver.com, www.google.com HTTP .

.
( or firefox) .
.
.

?
.
.

importunittest

if__name__=="__main__":
unittest.main()

unittest import main() .

classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)

test1 MiniWeb .
() MiniWeb .

MiniWeb .

wikidocs.net PDF, page : 244

classMiniWeb:
def__init__(self,port):
self.port=port

classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)


. 8080 .

classMiniWeb:
def__init__(self,port):
self.port=port
defstart(self):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("localhost",self.port))
s.listen(1)
conn,addr=s.accept()

classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)
miniweb.start()

start socket 8080 .


.

?
s.accept() s.accept() .

! Thread .

wikidocs.net PDF, page : 245

importunittest
importsocket
importthreading
classMiniWeb(threading.Thread):
def__init__(self,port):
threading.Thread.__init__(self)
self.port=port
defrun(self):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("localhost",self.port))
s.listen(1)
conn,addr=s.accept()

classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)
miniweb.start()

if__name__=="__main__":
unittest.main()

import threading Thread


start run . Thread start()
run() .
.
accept()
accept() . .

! .

importunittest
importsocket
importthreading
classMiniWeb(threading.Thread):
def__init__(self,port):
threading.Thread.__init__(self)

wikidocs.net PDF, page : 246

self.port=port
self.s=None
defrun(self):
self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.s.bind(("localhost",self.port))
self.s.listen(1)
conn,addr=self.s.accept()
defstop(self):
ifself.s:self.s.close()
classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)
miniweb.start()
miniweb.stop()

if__name__=="__main__":
unittest.main()

stop
.

start stop start stop


.

importtime
...
classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)
miniweb.start()
time.sleep(0.5)
miniweb.stop()

Interupt .
self.join() . while
.

wikidocs.net PDF, page : 247

importunittest
importsocket
importthreading
importtime
classMiniWeb(threading.Thread):
def__init__(self,port):
threading.Thread.__init__(self)
self.port=port
self.s=None
defrun(self):
self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.s.bind(("localhost",self.port))
self.s.listen(1)
while1:
try:
conn,addr=self.s.accept()
conn.close()
exceptsocket.error:
break
defstop(self):
ifself.s:self.s.close()
self.join()
classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)
miniweb.start()
time.sleep(0.5)
miniweb.stop()

if__name__=="__main__":
unittest.main()

wikidocs.net PDF, page : 248

classTestMiniWeb(unittest.TestCase):
deftest1(self):
miniweb=MiniWeb(port=8080)
miniweb.start()
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("localhost",8080))
s.send("abc")
s.close()
time.sleep(0.5)
miniweb.stop()

"abc" .
.

setUp tearDown
.

classTestMiniWeb(unittest.TestCase):
defsetUp(self):

self.server=MiniWeb(port=8080)
self.server.start()
deftearDown(self):
time.sleep(0.5)
self.server.stop()
deftest1(self):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("localhost",8080))
s.send("abc")
s.close()

wikidocs.net PDF, page : 249

HTTP .
.

HTTP/1.1 200 OK
Server: SimpleHttpServer
Content-type: text/plain
Content-Length: 2
HI

"HI"
.

...
defrun(self):
self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.s.bind(("localhost",self.port))
self.s.listen(1)
while1:
try:
conn,addr=self.s.accept()
recvmsg=conn.recv(1024)
conn.send(self.simpleResponse(recvmsg))
conn.close()
exceptsocket.error:
break
defsimpleResponse(self,msg):
return"""HTTP/1.1200OK
Server:SimpleHttpServer
Content-type:text/plain
Content-Length:%s
%s"""%(len(msg),msg)
...
deftest1(self):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("localhost",8080))
s.send("abc")
self.assertEquals(self.server.simpleResponse("abc"),s.recv(1024))
s.close()
...

wikidocs.net PDF, page : 250


.
.

if__name__=="__main__":
#unittest.main()
MiniWeb(port=8080).start()

http://localhost:8080 .

miniweb.py
importunittest

wikidocs.net PDF, page : 251

importsocket
importthreading
importtime
classMiniWeb(threading.Thread):
def__init__(self,port):
threading.Thread.__init__(self)
self.port=port
self.s=None
defrun(self):
self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.s.bind(("localhost",self.port))
self.s.listen(1)
while1:
try:
conn,addr=self.s.accept()
recvmsg=conn.recv(1024)
conn.send(self.simpleResponse(recvmsg))
conn.close()
exceptsocket.error:
break
defsimpleResponse(self,msg):
return"""HTTP/1.1200OK
Server:SimpleHttpServer
Content-type:text/plain
Content-Length:%s
%s"""%(len(msg),msg)
defstop(self):
ifself.s:self.s.close()
self.join()
classTestMiniWeb(unittest.TestCase):
defsetUp(self):
self.server=MiniWeb(port=8080)
self.server.start()
deftearDown(self):
time.sleep(0.5)
self.server.stop()

wikidocs.net PDF, page : 252

deftest1(self):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("localhost",8080))
s.send("abc")
self.assertEquals(self.server.simpleResponse("abc"),s.recv(1024))
s.close()

if__name__=="__main__":
#unittest.main()
MiniWeb(port=8080).start()

wikidocs.net PDF, page : 253

08.
(LAN Cable) .
.
.
.
, ?
.

image : http://ds.informatik.rwth-aachen.de/events/sciencesummer06/

()
, .

wikidocs.net PDF, page : 254

[1]
MySQL MySQL
MySQLdb . MySQL
MySQL . MySQL
.

MySQLdb
MySQLdb Mysql .
. www.mysql.com
. C:\mysql mysql
.

C:\mysql\bin\mysqld

mysql MySQLdb .
.

MySQLdb .
MySQLdb - http://sourceforge.net/projects/mysql-python/files

windows installer Gerhard's Homepage .


MySQLdb . MySQLdb-python-0.3.5-win32-2.zip(
) .

C:\temp\mysqldb-python-0.3.5>> python setup.py install

wikidocs.net PDF, page : 255

>>>importMySQLdb
>>>

MySQLdb .
MySQLdb -http://sourceforge.net/projects/mysql-python

.
MySQL-python-0.3.5.tar.gz

.
1. $ tar xvzf MySQL-python-0.3.5.tar.gz
2. $ cd MySQL-python-0.3.5
3. $ python setup.py build
4. # python setup.py install
install .

>>>importMySQLdb
>>>


MySQLdb .

wikidocs.net PDF, page : 256

C:\WINDOWS>cd \
C:\>cd mysql
C:\mysql>cd bin
C:\mysql\bin>mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 3.23.38
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
mysql>

- C:\mysql\bin>mysql mysqld
mysqld mysql .

book .

mysql>CREATEDATABASEbook;
QueryOK,1rowaffected(0.01sec)

book use .

mysql>usebook;
Databasechanged

mysql>createtableurllink(categoryvarchar(80),authorvarchar(80),
->subjectvarchar(80),urlvarchar(150));
QueryOK,0rowsaffected(0.01sec)

.
category :
author :

wikidocs.net PDF, page : 257

subject :
url : URL

mysql>describeurllink;
+----------+--------------+------+-----+---------+-------+
|Field|Type|Null|Key|Default|Extra|
+----------+--------------+------+-----+---------+-------+
|category|varchar(80)|YES||NULL||
|author|varchar(80)|YES||NULL||
|subject|varchar(80)|YES||NULL||
|url|varchar(150)|YES||NULL||
+----------+--------------+------+-----+---------+-------+
4rowsinset(0.05sec)

. mysql .

mysql>quit

. mysql .

MySQLdb
MySQLdb , connect host localhost db
book book m .

>>>importMySQLdb
>>>m=MySQLdb.connect(host='localhost',db='book')

( - user, passwd()

m=MySQLdb.connect(host='localhost',user='',passwd='',db='book')

m cursor c .

wikidocs.net PDF, page : 258

>>>c=m.cursor()

c .

>>>c.execute("select*fromurllink")
0L

c execute mysql>
.urllink
0L . 0L 'long int'.

. .
category : python
author : Eung-Yong
subject : EungYong HomePage
url : http://tdd.or.kr/tddlog

mysql>insertintourllinkvalues('python','Eung-Yong','EungYongHomepage','http://tdd.or.kr/tddlog')

. c
execute urllink .
1L .

>>>c.execute("select*fromurllink")
1L

c fetchall c.execute("select * from urllink")


. .

wikidocs.net PDF, page : 259

>>>c.fetchall()
(('python','Eung-Yong','EungYongHomePage','http://tdd.or.kr/tddlog'),)

MySQLdb . .
1. import MySQLdb .
2. MySQLdb.connect .
3. .
4. mysql fetchall .

fetchone . fetchall
readlines fetchone readline .

MySQL .

wikidocs.net PDF, page : 260

[2] django

"" .

(Spring), (Struts), ROR(Ruby On Rails) django


.
django .
django django django
.
(http://www.djangobook.com/en/2.0/) .
. ( " django")
django
django .
django ( ) . django
django ?
django
. django
.
django
? .
django .

wikidocs.net PDF, page : 261

01)
django .

?:

MVC


. django
:

Web (HTTP)
HTML


. ?
.

django
.

django book :
http://www.djangobook.com/en/2.0/


. .
.
.

"" " Django " :


http://wikidocs.net/mybook/read/index?pageid=4901

django
:
http://www.djangoproject.com/download/

wikidocs.net PDF, page : 262


:
Django-1.1.tar.gz

. tar.gz
.

C:\Django-1.1

C:\Django-1.1>c:\python2.6\pythonsetup.pyinstall

.
django-admin.py
. django-admin.py .

\python2.6\Lib\site-packages\django\bin

(django-admin.py) C:\work
.

C:\work>c:\python2.6\pythonc:\python2.6\Lib\site-packages\django\bin\django-admin.pystartprojectmysite

c:\work mysite
.
.

wikidocs.net PDF, page : 263

2009-07-2902:09557manage.py
2009-07-2902:092,852settings.py
2009-07-2902:09554urls.py
2009-07-2902:090__init__.py

C:\work\mysite>c:\python2.6\pythonmanage.pyrunserver
Validatingmodels...
0errorsfound
Djangoversion1.1,usingsettings'mysite.settings'
Developmentserverisrunningathttp://127.0.0.1:8000/
QuittheserverwithCTRL-BREAK.

127.0.0.1 8000 .

wikidocs.net PDF, page : 264

Hello World .
mysite views.py .
mysite\views.py

fromdjango.httpimportHttpResponse
defhello(request):
returnHttpResponse("Helloworld")

mysite urls.py .

fromdjango.conf.urls.defaultsimport*
frommysite.viewsimporthello
urlpatterns=patterns('',
('^hello/$',hello))

http://127.0.0.1:8000/hello "Hello World"


.

:
urls.py url . url regex()
views.py .
HttpResponse .

Hello World .

wikidocs.net PDF, page : 265

02) (Templates)
django . HTML
django .

django
django mysite/settings.py .
mysite/settings.py

TEMPLATE_DIRS=(
'C:/work/mysite/templates',
)

c:/work/mysite/templates .

test1.html .
( UTF-8 .
)
mysite/templates/test1.html

<html>
<head>
<title>djangoexample#1</title>
</head>
<body>
<p>
.
</p>
<p>
{{message}}
</p>
</body>
</html>

wikidocs.net PDF, page : 266

views.py .
mysite/views.py

#-*-coding:utf-8-*fromdjango.httpimportHttpResponse
fromdjango.template.loaderimportget_template
fromdjango.templateimportContext
defhello(request):
returnHttpResponse("Helloworld")
deftemplate_test(request):
t=get_template('test1.html')
html=t.render(Context({'message':""}))
returnHttpResponse(html)

urls.py .
mysite/urls.py

fromdjango.conf.urls.defaultsimport*
frommysite.viewsimporthello,template_test
urlpatterns=patterns('',
('^hello/$',hello),
('^test1/$',template_test),)

http://127.0.0.1:8000/test1 .
.

wikidocs.net PDF, page : 267

:
.
get_template Template .
get_template

fp=open('c:/work/mysite/templates/test1.html')
t=Template(fp.read())
fp.close()

Context .

.
.

.
mysite/templates/test1.html

wikidocs.net PDF, page : 268

<html>
<head>
<title>djangoexample#1</title>
</head>
<body>
<p>
.
</p>
<p>
{{message}}
</p>
<p>
.
</p>
<ul>
{%foriteminitem_list%}
<li>{{item}}</li>
{%endfor%}</ul>
</body>
</html>

views.py .
mysite/views.py

deftemplate_test(request):
t=get_template('test1.html')
c=Context({
'message':"",
"item_list":["one","two","three"],
})
html=t.render(c)
returnHttpResponse(html)

wikidocs.net PDF, page : 269


http://127.0.0.1:8000/test1 .

:
{% for .. %}, {% endfor %}

wikidocs.net PDF, page : 270

03) (Models)
?
.
"User" "", "", ""
.

classUser:
def__init__(self):
self.name=""
self.email=""
self.address=""

django ?

django "" .
django ?
SQL .
django SQL . SQL django
SQL .
. "". SQL
. SI
SQL . SQL django ?
?
django . django
.
django :
1. PC
2.

MySQL .
MySQL :
http://dev.mysql.com/get/Downloads/MySQL-5.1/mysql-essential-5.1.36-win32.msi/from/pick#mirrors

wikidocs.net PDF, page : 271

MySQL .
http://sourceforge.net/projects/mysql-python/

. ( .
)

django & Models


django Models .

- mypage_page

- pageid (int)

- page_name (varchar(100))

- page_content (text)


app
. app
app .

wikidocs.net PDF, page : 272

pythonmanage.pystartappmypage

C:\work\mysite>cdmypage
C:\work\mysite\mypage>dir
C.
:D075-1035
C:\work\mysite\mypage
2009-08-1005:18.
2009-08-1005:18..
2009-08-1005:1860models.py
2009-08-1005:18537tests.py
2009-08-1005:1827views.py
2009-08-1005:180__init__.py
4624
24,267,645,952

mypage 4 .

models.py .
mysite/mypage/models.py

fromdjango.dbimportmodels
#Createyourmodelshere.
classPage(models.Model):
pageid=models.IntegerField(primary_key=True)
page_name=models.CharField(max_length=100)
page_content=models.TextField()

wikidocs.net PDF, page : 273

[] - primary_key TextField .
. Field
(__init__) primary_key
. TextField, CharField Field
.

python2.6\Lib\site-packages\django\db\models\fields\__init__.py

classField(object):
#Designateswhetheremptystringsfundamentallyareallowedatthe
#databaselevel.
empty_strings_allowed=True
#ThesetrackeachtimeaFieldinstanceiscreated.Usedtoretainorder.
#Theauto_creation_counterisusedforfieldsthatDjangoimplicitly
#creates,creation_counterisusedforalluser-specifiedfields.
creation_counter=0
auto_creation_counter=-1
def__init__(self,verbose_name=None,name=None,primary_key=False,
max_length=None,unique=False,blank=False,null=False,
db_index=False,rel=None,default=NOT_PROVIDED,editable=True,
serialize=True,unique_for_date=None,unique_for_month=None,
unique_for_year=None,choices=None,help_text='',db_column=None,
db_tablespace=None,auto_created=False):

settings.py .
mysite/settings.py

DATABASE_ENGINE='mysql'#'postgresql_psycopg2','postgresql','mysql','sqlite3'or'oracle'.
DATABASE_NAME='django'#Orpathtodatabasefileifusingsqlite3.
DATABASE_USER='root'#Notusedwithsqlite3.
DATABASE_PASSWORD='1'#Notusedwithsqlite3.
DATABASE_HOST=''#Settoemptystringforlocalhost.Notusedwithsqlite3.
DATABASE_PORT=''#Settoemptystringfordefault.Notusedwithsqlite3.
INSTALLED_APPS=(
#'django.contrib.auth',
#'django.contrib.contenttypes',

wikidocs.net PDF, page : 274

#'django.contrib.sessions',
#'django.contrib.sites',
'mysite.mypage',
)

mysql . mysql .
, , . INSTALLED_APPS
mysite.mypage .

C:\work\mysite>c:\python2.6\pythonmanage.pysqlallmypage
c:\python2.6\lib\site-packages\MySQLdb\__init__.py:34:DeprecationWarnin
g:thesetsmoduleisdeprecated
fromsetsimportImmutableSet
BEGIN;
CREATETABLE`mypage_page`(
`pageid`integerNOTNULLPRIMARYKEY,
`page_name`varchar(100)NOTNULL,
`page_content`longtextNOTNULL
)
;
COMMIT;
C:\work\mysite>

manage.py sqlall SQL


.

SQL django .

C:\work\mysite>c:\python2.6\pythonmanage.pysyncdb
c:\python2.6\lib\site-packages\MySQLdb\__init__.py:34:DeprecationWarning:thesetsmoduleisdeprecated
fromsetsimportImmutableSet
Creatingtablemypage_page

syncdb .

wikidocs.net PDF, page : 275

mysql>descmypage_page;
+--------------+--------------+------+-----+---------+-------+
|Field|Type|Null|Key|Default|Extra|
+--------------+--------------+------+-----+---------+-------+
|pageid|int(11)|NO|PRI|||
|page_name|varchar(100)|NO||||
|page_content|longtext|NO||||
+--------------+--------------+------+-----+---------+-------+
3rowsinset(0.00sec)

.
. ( !)

C:\work\mysite>c:\python2.6\pythonmanage.pyshell

shell .

c:\python2.6\lib\site-packages\MySQLdb\__init__.py:34:DeprecationWarning:thesetsmoduleisdeprecated
fromsetsimportImmutableSet
Python2.6.2(r262:71605,Apr142009,22:40:02)[MSCv.150032bit(Intel)]onwin32
Type"help","copyright","credits"or"license"formoreinformation.
(InteractiveConsole)
>>>

shell .

frommypage.modelsimportPage
>>>p1=Page(pageid=1,page_name='testpage',page_content='testpagecontent')
>>>p1.save()

Page save .
.

wikidocs.net PDF, page : 276

mysql>select*frommypage_page;
+--------+-----------+-------------------+
|pageid|page_name|page_content|
+--------+-----------+-------------------+
|1|testpage|testpagecontent|
+--------+-----------+-------------------+
1rowinset(0.00sec)

p1.save() ?
?
.

p1.save() .

>>>p1.save()

.
. . save
?
save() .

p1 p2 save .
"".

>>>p2=Page(pageid=1,page_name='testpage',page_content='testpagecontent')
>>>p2.save()

. p3
save .

>>>p3=Page(pageid=2,page_name='testpage',page_content='testpagecontent')
>>>p3.save()

wikidocs.net PDF, page : 277

mysql>select*frommypage_page;
+--------+-----------+-------------------+
|pageid|page_name|page_content|
+--------+-----------+-------------------+
|1|testpage|testpagecontent|
|2|testpage|testpagecontent|
+--------+-----------+-------------------+
2rowsinset(0.00sec)

save
.

? . .

>>>p4=Page(pageid=3,page_name='',page_content='testpagecontent')
>>>p4.save()

. .
mysql .

mysql>select*frommypage_page;
+--------+-----------+-------------------+
|pageid|page_name|page_content|
+--------+-----------+-------------------+
|1|testpage|testpagecontent|
|2|testpage|testpagecontent|
|3|??|testpagecontent|
+--------+-----------+-------------------+
3rowsinset(0.00sec)

>>>page_list=Page.objects.all()
>>>page_list
[<Page:Pageobject>,<Page:Pageobject>,<Page:Pageobject>]

wikidocs.net PDF, page : 278

>>>forpageinpage_list:printpage.page_name
...
testpage
testpage

. mypage_page
pageid 1,2,3 max(pageid)+1
.

.
order_by .

>>>pageid_list=Page.objects.order_by("pageid")
>>>pageid_list
[<Page:Pageobject>,<Page:Pageobject>,<Page:Pageobject>]

pageid order_by pageid .

-1 .

>>>pageid_list[-1].pageid
Traceback(mostrecentcalllast):
File"",line1,in
File"c:\python2.6\lib\site-packages\django\db\models\query.py",line126,in__getitem__
"Negativeindexingisnotsupported."
AssertionError:Negativeindexingisnotsupported.

Negative . .
? .

wikidocs.net PDF, page : 279

>>>page_list[len(page_list)-1].pageid
3L

len(page_list)-1 . 3+1
4 .
. max(pageid)+1 order by
.

oder by desc limit 1 max .

>>>Page.objects.order_by("-pageid")[0].pageid
3L

desc "-" .

SQL .

selectmax(pageid)+1frommypage_page

. .

>>>fromdjango.db.modelsimportMax
>>>Page.objects.all().aggregate(Max("pageid"))
{'pageid__max':3}

.
filter get
. filter, get like join subquery
,,, .
.

wikidocs.net PDF, page : 280

04) (Forms)
(Forms) .

(Forms) . (
..)
HTML form .

HTML .

<formname="pageform"action="/save_page/"method="post">
<inputtype="text"name="page_name"id="page_name"/>
<textareaname="page_content"id="page_content"rows="5"cols="20"></textarea>
</form>

, /save_page/ URL .

.
HTML .
mysite/views.py

#-*-coding:utf-8-*fromdjango.httpimportHttpResponse
fromdjango.template.loaderimportget_template
fromdjango.templateimportContext
frommypage.modelsimportPage
...
defpage_form(request):
t=get_template('page_form.html')
returnHttpResponse(t.render(Context({})))

mysite/urls.py

fromdjango.conf.urls.defaultsimport*
frommysite.viewsimporthello,page_form

wikidocs.net PDF, page : 281

urlpatterns=patterns('',
('^hello/$',hello),
('^page_form/$',page_form),
)

mysite/templates/page_form.html

<html>
<head>
<title>pageform</title>
</head>
<body>
<formname="pageform"action="/save_page/"method="post">
<table>
<tr>
<td></td>
<td>
<inputtype="text"name="page_name"id="page_name"/>
</td>
</tr>
<tr>
<td></td>
<td>
<textareaname="page_content"id="page_content"rows="5"cols="20"></textarea>
</td>
</tr>
<tr>
<tdcolspan="2">
<inputtype="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>

http://localhost:8000/page_form/
.

wikidocs.net PDF, page : 282


"" /save_page URL .

.
mysite/views.py

#-*-coding:utf-8-*fromdjango.httpimportHttpResponse
fromdjango.template.loaderimportget_template
fromdjango.templateimportContext
frommypage.modelsimportPage
fromdjango.db.modelsimportMax
...
defsave_page(request):
page_name=request.POST['page_name']
page_content=request.POST['page_content']
pageid=int(Page.objects.all().aggregate(Max("pageid")).get("pageid__max"))+1
page=Page(pageid=pageid,page_name=page_name,page_content=page_content)
page.save()
returnpage_form(request)

post request.POST[''] . get


request.GET[''] .

mysite/urls.py

wikidocs.net PDF, page : 283

fromdjango.conf.urls.defaultsimport*
frommysite.viewsimporthello,page_form,save_page
urlpatterns=patterns('',
('^hello/$',hello),
('^page_form/$',page_form),
('^save_page/$',save_page),
)

"Submit"
.

.
from django import forms .
.

wikidocs.net PDF, page : 284

05) (Sessions)
.
(Cookie) .
HTTP .
"" .

[ - ]

HTTP
. "".

HTTP
. HTML .
HTML . .

.

. (Cookie).

. HTTP
Cookie . Cookie
. ()
.


(Sessions).
.

.
settings.py .
mysite/settings.py

wikidocs.net PDF, page : 285

MIDDLEWARE_CLASSES=(
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
)
INSTALLED_APPS=(
...
'django.contrib.sessions',
...
)

django_session .

C:\work\mysite>c:\python2.6\pythonmanage.pysyncdb
c:\python2.6\lib\site-packages\MySQLdb\__init__.py:34:DeprecationWarning:thesetsmoduleisdeprecated
fromsetsimportImmutableSet
Creatingtabledjango_session

mysql>descdjango_session;
+--------------+-------------+------+-----+---------+-------+
|Field|Type|Null|Key|Default|Extra|
+--------------+-------------+------+-----+---------+-------+
|session_key|varchar(40)|NO|PRI|||
|session_data|longtext|NO||||
|expire_date|datetime|NO||||
+--------------+-------------+------+-----+---------+-------+
3rowsinset(0.00sec)

.
mysite/urls.py

wikidocs.net PDF, page : 286

fromdjango.conf.urls.defaultsimport*
frommysite.viewsimporthello,page_form,save_page,session_test
urlpatterns=patterns('',
...
('^session_test/$',session_test),
)

mysite/views.py

defsession_test(request):
ifrequest.GET.has_key("data"):
request.session['data']=request.GET['data']
ifnotrequest.session.has_key('data'):
returnHttpResponse(u".")
else:
returnHttpResponse(u":%s"%request.session['data'])

" " Get .


.

URL .

http://localhost:8000/session_test/?data=ok

data "ok" .

2 .
django_session expire_date 2
.
.

mysite/settins.py

SESSION_EXPIRE_AT_BROWSER_CLOSE=True

wikidocs.net PDF, page : 287

06)
. .

.
django .
!
.
django
.
.
"".
"" .
pahkey@gmail.com

wikidocs.net PDF, page : 288

09. Tips
Tips .

wikidocs.net PDF, page : 289

[01] API
.
" " .

. OpenAPI .

1.
.

OpenAPI OpenAPI .
URL URL .(
.)
http://flickr.com/services/api/keys/
( URL: http://lab.pyframe.org/example/openapi/flickrcallback)

multipart/form .

<formname="imageForm"action="/example/openapi/upload"method="post"enctype="multipart/form-data">

form submit (:/example/openapi/upload) .


( .)

/example/openapi/upload

importmd5
...
defupload(self):
filename,content=self.getfile("filename")
session=self.getSession()
session['file_content']=content
session['file_filename']=filename

wikidocs.net PDF, page : 290

m=md5.new()
sig="%sapi_key%sperms%s"%(API_SECRET,API_KEY,"write")
m.update(sig)
api_sig=m.hexdigest()
authurl="http://www.flickr.com/services/auth/?api_key=%s&perms=write&api_sig=%s"\
%(self.getAppCfg().API_KEY,api_sig)
self.redirect(authurl)

self.getfile pyframe API .


( pyframe .)
authurl authurl .
authurl API_SECRET, API_KEY flickr .
flickr callback URL .
(: /example/openapi/flickrcallback)

callback .

/example/openapi/flickrcallback

importflickrapi
...

defflickrcallback(self):
m=md5.new()
frob=self.get("frob")
sig="%sapi_key%sfrob%smethodflickr.auth.getToken"%\
(API_SECRET,API_KEY,frob)
m.update(sig)
api_sig=m.hexdigest()
authurl="http://api.flickr.com/services/rest/?method=flickr.auth.getToken&api_key=%s&frob=%s&api_sig=
(API_KEY,frob,api_sig)
f=urllib2.urlopen(authurl)
data=f.read()
f.close()
t=flickrapi.XMLNode.parseXML(data)
flickr_token=t.auth[0].token[0].elementText
flickr=flickrapi.FlickrAPI(API_KEY,API_SECRET)
flickr.token=flickr_token

wikidocs.net PDF, page : 291

session=self.getSession()
content=session['file_content']
filename=session['file_filename']
r=flickr.upload(filename=filename,payload=content,callback=None)
photoid=r.photoid[0].elementText
xmlnode=flickr.photos_getSizes(photo_id=photoid)
p=flickrapi.XMLNode.parseXML(xmlnode.xml)
imageurl=str(p.sizes[0].size[-1].attrib["source"])
delsession['file_content']
delsession['file_filename']

API flickrapi .
see also :http://flickrapi.sourceforge.net/flickrapi.html

flickr.upload ( ) .
photoid imageurl . (
photoid . flickrapi
)
imageurl .

2.
(picasa)
.
,
open api
.
picasa api gdata .
http://code.google.com/p/gdata-python-client/downloads/list

Picasa .
. .

wikidocs.net PDF, page : 292

multipart/form .

<formname="imageForm"action="/example/openapi/upload"method="post"enctype="multipart/form-data">

form submit (:/example/openapi/upload) .


.

/example/openapi/upload

importgdata.photos.service
importgdata.media
importgdata.geo
...
defupload(self):
filename,content=self.getfile("filename")
session=self.getSession()
session['file_content']=content
session['file_filename']=filename
authSubUrl=self.picasaAuth()
self.redirect(authSubUrl)

defpicasaAuth(self):
next='http://%s/example/openapi/picasaAuthAfter'\
%self.getAppCfg().DOMAIN_NAME
scope='http://picasaweb.google.com/data/'
secure=False
session=True
gd_client=gdata.photos.service.PhotosService()
returngd_client.GenerateAuthSubURL(next,scope,secure,session)

upload .
picasaAuth . picasa api .
picasaAuthAfter next URL .

/example/openapi/picasaAuthAfter

defpicasaAuthAfter(self):
authsub_token=self.get("token")

wikidocs.net PDF, page : 293

#tokenupdate
gd_client=gdata.photos.service.PhotosService()
gd_client.auth_token=authsub_token
gd_client.UpgradeToSessionToken()
#addalbum
#entry=gd_client.InsertAlbum('example','example')
session=self.getSession()
content=session['file_content']
filename=session['file_filename']
f=cStringIO.StringIO(content)
album_url='/data/feed/api/user/%s/album/%s'%("default","example")
entry=gd_client.InsertPhotoSimple(album_url,filename,
'Uploadedbyexample',f,content_type='image/jpeg')
delsession['file_content']
delsession['file_filename']
self.redirect(entry.content.src)

picasaAuthAfter token
.

api .

gd_client.InsertAlbum('example','example')

InsertAlbum . picasa
example . ( (?)
.) api api .
.

API .

wikidocs.net PDF, page : 294

[02]
1.
postgresql .

backup.sh

#!/bin/bash
#---------------------------------------------------------------#pg_dump&restore
#[postgrespostgres]$pg_dump-Fc-fmydb.dumpmydb
#[postgrespostgres]$dropdbmydb
#[postgrespostgres]$pg_restore-Fc-C-dtemplate1mydb.dump
#---------------------------------------------------------------BACKUP_DIR=/var/lib/postgresql/backup
DB_NAME=mydb
DATE=$(date+%Y%m%d)
/usr/bin/pg_dump-Fc-f$BACKUP_DIR/$DB_NAME.$DATE.dump$DB_NAME

backup.sh mydb /var/lib/postgresql/backup


mydb.YYYYMMDD.dump . (YYYYMMDD sh )
sh .

2.
email_backup.py

#!/usr/bin/envpython
#-*-coding:utf-8-*#Importsmtplibfortheactualsendingfunction
importsmtplib
importtime
importglob
importmimetypes
#Herearetheemailpackagemoduleswe'llneed

wikidocs.net PDF, page : 295

fromemail.mime.baseimportMIMEBase
fromemail.mime.multipartimportMIMEMultipart
fromemailimportencoders
BACKUP_DIR="/var/lib/postgresql/backup"
deftodaytime(fmt):returntime.strftime(fmt)

#Createthecontainer(outer)emailmessage.
msg=MIMEMultipart()
msg['Subject']='BACKUPMYDB[%s]'%todaytime("%Y/%m/%d")
#me==thesender'semailaddress
#family=thelistofallrecipients'emailaddresses
msg['From']=""
msg['To']="pahkey@gmail.com"
filenames=glob.glob("%s/*%s*"%(BACKUP_DIR,todaytime("%Y%m%d")))
forfilenameinfilenames:
ctype='application/octet-stream'
maintype,subtype=ctype.split('/',1)
mb=MIMEBase(maintype,subtype)
fp=open(filename,'rb')
mb.set_payload(fp.read())
fp.close()
encoders.encode_base64(mb)
mb.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(mb)

mailServer=smtplib.SMTP("smtp.gmail.com")
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login("","")
mailServer.sendmail(msg["From"],msg["To"],msg.as_string())

(Gmail) .
.

wikidocs.net PDF, page : 296

3. crontab

0003***/var/lib/postgresql/backup.sh
2003***/var/lib/postgresql/email_backup.py

3 backup.sh 3 20 .

wikidocs.net PDF, page : 297

[03]
.
?
Copy & Paste. Copy & Paste
.
MetaWebLogApi.
MetaWebLogApi API, . ,
MetaWebLogApi . ,
.
MetaWebLogApi .
(MetaWebLogApi XML-RPC . XML-RPC .)

1.

metaWeblog.newPost (blogid, username, password, struct, publish)


returns string

metaWeblog XML-RPC .
metaWeblog .

metaWeblog=xmlrpclib.Server("http://pahkey.tistory.com/api").metaWeblog#

5.
1. blogid : ( , .
)
2. username : ( )
3. password : ( ,
)
4. struct : (, ..)
5. publish : ,

struct .
category :

wikidocs.net PDF, page : 298

description :
title :
( struct . mt_keywords()
.)

struct .

datastruct={'category':'','description':'','title':'.'}

postid( id) .

2.

metaWeblog.editPost (postid, username, password, struct, publish)


returns true

5.
postid - id
4

postid
.
boolean .

3.

metaWeblog.getPost (postid, username, password) returns struct

3.

wikidocs.net PDF, page : 299

postid - id
2

struct .
category :
description :
title :

URL .
http://www.xmlrpc.com/metaWeblogApi

MetaWebLog API .

#-*-coding:utf-8-*importxmlrpclib
#tistory
tistory=xmlrpclib.Server("http://pahkey.tistory.com/api")
datastruct={'category':'','description':".",
'title':'.',"mt_keywords":"mytodo,"}
no=tistory.metaWeblog.newPost("blogid","username",
"passwd",datastruct,True)
r=tistory.metaWeblog.getPost(no,"username","passwd")
printr
#egloos
egloos=xmlrpclib.Server("https://rpc.egloos.com/rpc1")
datastruct={'category':'','description':".",
'title':'.'}
no=egloos.metaWeblog.newPost("","username","passwd",datastruct,True)
r=egloos.metaWeblog.getPost(no,"username","passwd")
printr

wikidocs.net PDF, page : 300

[04] SMS
SMS .
SMS ( ) .
.
.
SMS
.
, ?
.
.

#-*-coding:utf-8-*try:
fromxml.etreeimportElementTree#forPython2.5users
exceptImportError:
fromelementtreeimportElementTree
importgdata.calendar.service
importgdata.service
importatom.service
importgdata.calendar
importatom
importgetopt
importsys
importstring
importtime

classGoogleCalendarSMS:
def__init__(self,email,password):
self.cs=gdata.calendar.service.CalendarService()
self.cs.email=email
self.cs.password=password
self.cs.source="mytodo"
self.cs.ProgrammaticLogin()
defsend(self,calendar_name,sms_content,sms_time='',reminder_use=True):
calendar=self.get_calendar(calendar_name)
event=gdata.calendar.CalendarEventEntry()

wikidocs.net PDF, page : 301

event.title=atom.Title(text=sms_content)
event.content=atom.Content(text="")
#event.where.append(gdata.calendar.Where(value_string=calendar_name))
ifnotsms_time:
sms_time=time.strftime('%Y-%m-%dT%H:%M:%S.000Z',time.gmtime(time.time()+60))#1minlater.
event.when.append(gdata.calendar.When(
start_time=sms_time,end_time=sms_time))
ifreminder_use:
reminder=gdata.calendar.Reminder(minutes='0')
reminder._attributes['method']='method'
reminder.method='sms'
event.when[0].reminder.append(reminder)
returnself.cs.InsertEvent(event,calendar.GetAlternateLink().href)
defsenddate(self,calendar_name,sms_content,stime,etime):
calendar=self.get_calendar(calendar_name)
event=gdata.calendar.CalendarEventEntry()
event.title=atom.Title(text=sms_content)
event.content=atom.Content(text="")
event.where.append(gdata.calendar.Where(value_string=calendar_name))
event.when.append(gdata.calendar.When(
start_time=stime,end_time=etime))
returnself.cs.InsertEvent(event,calendar.GetAlternateLink().href)
defget_calendar(self,calendar_name):
feed=self.cs.GetAllCalendarsFeed()
fori,a_calendarinenumerate(feed.entry):
ifa_calendar.title.text==calendar_name:
returna_calendar
calendar=gdata.calendar.CalendarListEntry()
calendar.title=atom.Title(text=calendar_name)
calendar.summary=atom.Summary(text=calendar_name)
returnself.cs.InsertCalendar(new_calendar=calendar)

if__name__=="__main__":
gss=GoogleCalendarSMS("pahkey@gmail.com","xxxxxxxx")#parameter:,
gss.send("MYTODO","")#parameter:,SMS

wikidocs.net PDF, page : 302

gss=GoogleCalendarSMS("pahkey@gmail.com","xxxxxxxx")#parameter:,
gss.send("MYTODO","")#parameter:,SMS

SMS
.
URL .
http://googlekoreablog.blogspot.com/2008/08/google.html

API .
http://code.google.com/p/gdata-python-client/

(http://mytodo.org) TODO
SMS .

wikidocs.net PDF, page : 303

10. Quiz
Quiz.

Quiz .
.
( )

wikidocs.net PDF, page : 304

[01]
.

[]

.
.
(nested list) .

, .
.

[1, 2, [3, 4, [5]], 6, [[7,8]]]

, , F
.

, [1, 2, 3, 4, 5, 6, 7, 8] .

[]

. 2
. .
.
.

,
, ? (
F --
)

[]

wikidocs.net PDF, page : 305

result=[]
defforLife(l):
foriteminl:
iftype(item)==list:
forLife(item)
else:
result.append(item)
forLife([1,2,[3,4,[5]],6,[[7,8]]])
printresult

wikidocs.net PDF, page : 306

[02]
[]

n , d(n) n n
.

d(91) = 9 + 1 + 91 = 101

, n d(n) (generator) . 91 101


.

, 101 91
100 . , ,
Kaprekar (self-number) .
1,3,5,7,9,20,31 .

1 5000 .

[]

#-*-coding:euc-kr-*importunittest
defadd_digit(no):
returnsum(map(int,''.join(str(no)).split()))
deff(no):
returnadd_digit(no)+no
refer={}
foriinrange(1,5001):refer[i]=f(i)
defgetgen(no):
result=[]
forninrange(1,no+1):
#iff(n)==no:result.append(n)

wikidocs.net PDF, page : 307

ifrefer[n]==no:result.append(n)
returnresult
defselfno(limit):
result=[]
foriinrange(1,limit+1):
ifnotgetgen(i):result.append(i)
returnresult

classGeneratorTest(unittest.TestCase):
deftest1(self):
self.assertEquals(2,add_digit(200))
self.assertEquals(10,add_digit(91))
self.assertEquals(101,f(91))
self.assertEquals(101,f(100))
self.assertEquals([1],getgen(2))
self.assertEquals([91,100],getgen(101))
self.assertEquals([1,3,5,7,9],selfno(10))
print"result:",sum(selfno(5000))
if__name__=="__main__":
unittest.main()

wikidocs.net PDF, page : 308

[03] PrimaryArithmetic
About PrimaryArithmetic

. 10 1
.
.

Input

. '0
0' .

output

Sample Input

123 456

555 555

123 594

0 0

Sample Output

wikidocs.net PDF, page : 309

No carry operation.

3 carry operations.

1 carry operation.

[]

importunittest
classNumber:
def__init__(self,num):
self.num=list(str(num))
def__getitem__(self,index):
try:returnint(self.num[index])
exceptIndexError:return0
def__len__(self):
returnlen(self.num)
classAdder:
def__init__(self):
self.carries=[0]*10
defadd(self,src,target):
foriinrange(1,max(len(src),len(target))+1):
ifsrc[-i]+target[-i]+self.carries[-i]>=10:
self.carries[-i-1]=1
defcarryCount(self):
returnself.carries.count(1)

classCarryTest(unittest.TestCase):
deftest1(self):
adder=Adder()
adder.add(Number(1),Number(1))
self.assertEquals(0,adder.carryCount())
deftest2(self):
adder=Adder()
adder.add(Number(9),Number(1))
self.assertEquals(1,adder.carryCount())

wikidocs.net PDF, page : 310

deftest3(self):
adder=Adder()
adder.add(Number(99),Number(1))
self.assertEquals(2,adder.carryCount())
deftest4(self):
adder=Adder()
adder.add(Number(899),Number(1))
self.assertEquals(2,adder.carryCount())
deftest5(self):
adder=Adder()
adder.add(Number(555),Number(555))
self.assertEquals(3,adder.carryCount())
deftest6(self):
adder=Adder()
adder.add(Number(123),Number(594))
self.assertEquals(1,adder.carryCount())
importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(CarryTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

wikidocs.net PDF, page : 311

[04] Spiral Array


Spiral Array
.

6 6
0
19
18
17
16
15

1
20
31
30
29
14

2
21
32
35
28
13

3
22
33
34
27
12

4
23
24
25
26
11

5
6
7
8
9
10

6 6 6X6 .

[]
. .
, .
Direction , Spiral Array .
changeDirection,
. sin
.

importunittest
"""
66
012345
19202122236
18313233247
17303534258
16292827269
151413121110
"""

wikidocs.net PDF, page : 312

classSpiralArray:
def__init__(self,row,col):
self.maxcol=col-1
self.maxrow=row-1
self.factors={
"right":(0,1),
"down":(1,0),
"left":(0,-1),
"up":(-1,0)
}
self.init()
definit(self):
self.cur=0
self.curPoint=0,0
self.map={}
forrinrange(self.maxrow+1):
forcinrange(self.maxcol+1):
self.map[r,c]=-1
self.map[self.curPoint]=0
self.setDirection("right")
defsetDirection(self,direction):
self.directFactor=direction
defgetDirection(self):
returnself.directFactor
defgetCol(self):
returnself.curPoint[1]
defgetRow(self):
returnself.curPoint[0]
defisDown(self,nextPoint):
returnself.getDirection()=="right"\
and(self.getCol()==self.maxcolorself.hasValue(nextPoint))
defisLeft(self,nextPoint):
returnself.getDirection()=="down"\
and(self.getRow()==self.maxroworself.hasValue(nextPoint))
defisUp(self,nextPoint):
returnself.getDirection()=="left"\
and(self.getCol()==0orself.hasValue(nextPoint))
defisRight(self,nextPoint):
returnself.getDirection()=="up"\
and(self.getRow()==0orself.hasValue(nextPoint))
defchangeDirection(self):
nextPoint=self.nextPoint()
ifself.isDown(nextPoint):self.setDirection("down")

wikidocs.net PDF, page : 313

elifself.isLeft(nextPoint):self.setDirection("left")
elifself.isUp(nextPoint):self.setDirection("up")
elifself.isRight(nextPoint):self.setDirection("right")
defnextPoint(self):
factor=self.factors[self.directFactor]
returnself.getRow()+factor[0],self.getCol()+factor[1]
defallPointed(self):
returnself.map.values().count(-1)==0
defpoint(self):
ifself.allPointed():raiseRuntimeError()
self.changeDirection()
self.curPoint=self.nextPoint()
self.cur+=1
self.setValue(self.curPoint)
defhasValue(self,point):
returnself.getValue(point)!=-1
defsetValue(self,point):
self.map[point[0],point[1]]=self.cur
defgetValue(self,point):
returnself.map[point[0],point[1]]
defrun(self):
while1:
try:self.point()
except:break
def__str__(self):
result=[]
forrowinrange(self.maxrow+1):
forcolinrange(self.maxcol+1):
result.append("%4s"%self.map[row,col])
result.append('\n')
return''.join(result)

classSpiralArrayTest(unittest.TestCase):
deftestChangeDirect(self):
sa=SpiralArray(2,2)
self.assertEquals((0,0),sa.curPoint)
sa.setDirection("right")
sa.point()
self.assertEquals((0,1),sa.curPoint)
sa.point()
self.assertEquals(1,sa.getValue((0,1)))
self.assertEquals((1,1),sa.curPoint)
sa.point()

wikidocs.net PDF, page : 314

self.assertEquals((1,0),sa.curPoint)
try:
sa.point()
self.fail("shouldnotreachhere")
except:
pass
deftest1(self):
sa=SpiralArray(6,6)
sa.run()
printsa
importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(SpiralArrayTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

wikidocs.net PDF, page : 315

[05] Four Boxes


[]

4 .
.
.
, . RECT.EXE .

.
, .
x, y,
x, y., x y
1 1000 .

4 .

1 2 4 4

2 3 5 7
3 1 6 5
7 3 8 6

wikidocs.net PDF, page : 316

26

[]
.

n(AUBUCUD) = n(A)+n(B)+n(C)+n(D)
-(n(AB)+n(AC)+n(AD)+n(BC)+n(BD)+n(CD))
+(n(ABC)+n(ABD)+n(ACD)+n(BCD))
-n(ABCD)

intersect Rect intersect


. combination comb . (generator
.)

importunittest
classRectError(RuntimeError):
pass
classRect:
def__init__(self,lx,ly,rx,ry):
self.lx=lx
self.ly=ly
self.rx=rx
self.ry=ry
defsize(self):
returnabs(self.rx-self.lx)*abs(self.ry-self.ly)
defintersect(self,other):
try:
lx,rx=self.get(self.lx,self.rx,other.lx,other.rx)

wikidocs.net PDF, page : 317

ly,ry=self.get(self.ly,self.ry,other.ly,other.ry)
returnRect(lx,ly,rx,ry)
exceptRectError:
returnRect(0,0,0,0)
def__eq__(self,other):
returnself.lx==other.lx\
andself.ly==other.ly\
andself.rx==other.rx\
andself.ry==other.ry
def__repr__(self):
returnstr((self.lx,self.ly))+str((self.rx,self.ry))
defget(self,sleft,sright,oleft,oright):
ifoleft<=sleft<=oright:
ifsright<=oright:returnsleft,sright
else:returnsleft,oright
elifsleft<=oleft<=sright:
iforight<=sright:returnoleft,oright
else:returnoleft,sright
else:
raiseRectError("intersectiondoesnotexists!")

defcomb(fromSet,choice):
ifchoice==0:
yield[]
else:
fori,pivotinenumerate(fromSet):
foreachincomb(fromSet[i+1:],choice-1):
yield[pivot]+each
defintersectSum(*rect):
result=0
forrectGroupinrect:
fortargetRectinrectGroup:
seed=targetRect[0]
fortintargetRect[1:]:
seed=seed.intersect(t)
result+=seed.size()
returnresult
defcalc(*rect):

wikidocs.net PDF, page : 318

result=0
foriinrange(len(rect)):
sign=i%2and-1or1
result+=sign*intersectSum(comb(rect,i+1))
returnresult

classSumOfRectTest(unittest.TestCase):
deftestTwoRectNoIntersect(self):
A=Rect(0,0,1,1)
B=Rect(1,1,2,2)
self.assertEquals(2,A.size()+B.size())
self.assertEquals(0,A.intersect(B).size())
deftestTwoRectIntersect(self):
A=Rect(0,0,2,2)
B=Rect(1,1,3,3)
self.assertEquals(8,A.size()+B.size())
self.assertEquals(1,A.intersect(B).size())
deftestInterSect1(self):
A=Rect(0,0,2,2)
B=Rect(1,1,3,3)
C=Rect(1,1,2,2)
self.assertEquals(C,A.intersect(B))
self.assertEquals(C,B.intersect(A))
self.assertEquals(C,A.intersect(C))
self.assertEquals(C,C.intersect(B))
self.assertEquals(C,C.intersect(A))
self.assertEquals(C,B.intersect(C))
deftestThreeRect1(self):
A=Rect(-1,-1,1,1)
B=Rect(0,0,2,2)
C=Rect(1,1,3,3)
self.assertEquals(4+4+4,A.size()+B.size()+C.size())
self.assertEquals(1,A.intersect(B).size())
self.assertEquals(1,B.intersect(C).size())
self.assertEquals(0,A.intersect(C).size())
self.assertEquals(0,A.intersect(B).intersect(C).size())
deftestThreeRect2(self):
A=Rect(0,0,2,2)
B=Rect(1,1,3,3)

wikidocs.net PDF, page : 319

C=Rect(0,1,2,3)
self.assertEquals(1,A.intersect(B).intersect(C).size())
deftestFourRect1(self):
A=Rect(0,0,2,2)
B=Rect(1,1,3,3)
C=Rect(1,0,3,2)
D=Rect(-1,0,1,3)
self.assertEquals(0,A.intersect(B).intersect(C).intersect(D).size())
self.assertEquals(1,A.intersect(B).size())
self.assertEquals(2,A.intersect(C).size())
self.assertEquals(2,A.intersect(D).size())
self.assertEquals(2,B.intersect(C).size())
self.assertEquals(0,B.intersect(D).size())
self.assertEquals(0,C.intersect(D).size())
self.assertEquals(1,A.intersect(B).intersect(C).size())
self.assertEquals(4+4+4+6,A.size()+B.size()+C.size()+D.size())
self.assertEquals(12,A.size()+B.size()+C.size()+D.size()-(1+2+2+2+0+0)+1)
deftestFourRect2(self):
A=Rect(0,0,2,2)
B=Rect(0,-1,2,1)
C=Rect(-1,-1,1,1)
D=Rect(-1,0,1,2)
self.assertEquals(2,A.intersect(B).size())
self.assertEquals(1,A.intersect(C).size())
self.assertEquals(2,A.intersect(D).size())
self.assertEquals(2,B.intersect(C).size())
self.assertEquals(1,B.intersect(D).size())
self.assertEquals(2,C.intersect(D).size())
self.assertEquals(1,A.intersect(B).intersect(C).size())
self.assertEquals(1,A.intersect(B).intersect(D).size())
self.assertEquals(1,A.intersect(C).intersect(D).size())
self.assertEquals(1,B.intersect(C).intersect(D).size())
self.assertEquals(1,A.intersect(B).intersect(C).intersect(D).size())
self.assertEquals(4+4+4+4,A.size()+B.size()+C.size()+D.size())
self.assertEquals(9,4+4+4+4-(2+1+2+2+1+2)+(1+1+1+1)-1)
self.assertEquals(9,calc(A,B,C,D))
deftest1(self):
A=Rect(0,0,2,1)
B=Rect(0,0,1,2)
C=Rect(-1,-1,1,1)
D=Rect(-2,0,-1,3)

wikidocs.net PDF, page : 320

self.assertEquals(9,calc(A,B,C,D))
deftest2(self):
A=Rect(0,0,2,2)
B=Rect(1,1,3,3)
C=Rect(2,2,4,4)
D=Rect(3,3,5,5)
self.assertEquals(13,calc(A,B,C,D))
deftest3(self):
A=Rect(1,2,4,4)
B=Rect(2,3,5,7)
C=Rect(3,1,6,5)
D=Rect(7,3,8,6)
E=Rect(1,2,4,4)
self.assertEquals(26,calc(A,B,C,D,E))

importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(SumOfRectTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

.
.
~


cell .
, .

classRectBox:
def__init__(self):
self.box={}
defadd(self,x1,y1,x2,y2):
forxinrange(x1,x2):

wikidocs.net PDF, page : 321

foryinrange(y1,y2):
self.box[(x,y)]=1
defarea(self):
returnlen(self.box)

wikidocs.net PDF, page : 322

[06] Slurpy
Slurpy
(Slurpy) .
.

(Slump) .
1. 'D' 'E'.
2. 'F' .
3. 'F' 'G' . 'F' 'G'
. ,DFFEFFFG 'D' 'F' ,
'EFFFG' .
4. .

(Slimp) .
1. 'A'.
2. , 'H'.
3. .
'A' + 'B' + + 'C'.
'A' + + 'C'.
4. .

(Slurpy) (Slimp) (Slump) .

Slumps : DFG, EFG, DFFFFFG, DFDFDFDFG, DFEFFFFFG


Not Slumps: DFEFF, EFAHG, DEFG, DG, EFFFFDG
Slimps: AH, ABAHC, ABABAHCC, ADFGC, ADFFFFGC, ABAEFGCC, ADFDFGC
Not Slimps: ABC, ABAH, DFGC, ABABAHC, SLIMP, ADGC
Slurpys: AHDFG, ADFGCDFFFFFG, ABAEFGCCDFEFFFFFG
Not Slurpys: AHDFGA, DFGAH, ABABCC

wikidocs.net PDF, page : 323

N 1 ~ 10 .

N . 1 ~ 60
.

"SLURPYS OUTPUT" . N
"YES" "NO" . "END OF OUTPUT"
.

Sample Input

AHDFG

DFGAH

Sample Output

SLURPYS OUTPUT
YES
NO
END OF OUTPUT

[]

#-*-coding:euc-kr-*'''

wikidocs.net PDF, page : 324

*slurpy(slimpandslump)
*slump-(DorE)andF+and(slumporG)
*slimp-Aand(Hor((BandslimpandC)or(slumpandC))
**findslurpy!
[example]
Slumps:DFG,EFG,DFFFFFG,DFDFDFDFG,DFEFFFFFG
NotSlumps:DFEFF,EFAHG,DEFG,DG,EFFFFDG
Slimps:AH,ABAHC,ABABAHCC,ADFGC,ADFFFFGC,ABAEFGCC,ADFDFGC
NotSlimps:ABC,ABAH,DFGC,ABABAHC,SLIMP,ADGC
Slurpys:AHDFG,ADFGCDFFFFFG,ABAEFGCCDFEFFFFFG
NotSlurpys:AHDFGA,DFGAH,ABABCC
'''
importunittest

classUnitPattern:
def__init__(self,*args):
self.args=args
self._remain=''
defmatch(self,target):
raiseNotImplementedError
defremain(self):
returnself._remain

classWord(UnitPattern):
defmatch(self,target):
ifnottarget:returnFalse
self._remain=target[1:]
returnself.args[0][0]==target[0]

classAnd(UnitPattern):
defmatch(self,target):
forarginself.args:
ifnotarg.match(target):
returnFalse

wikidocs.net PDF, page : 325

target=arg.remain()
self._remain=target
returnTrue

classOr(UnitPattern):
defmatch(self,target):
forarginself.args:
ifarg.match(target):
self._remain=arg.remain()
returnTrue
returnFalse

classMore(UnitPattern):
defmatch(self,target):
ifnottarget:returnFalse
moreword=self.args[0][0]
forcount,tinenumerate(target):
ift!=moreword:
ifcount==0:returnFalse
break
self._remain=target[count:]
returnTrue

classMultiPattern:
defmatch(self,target):
returnself.pat.match(target)
defremain(self):
returnself.pat.remain()

classSlump(MultiPattern):
'''slump-(DorE)andF+and(slumporG)'''
def__init__(self):
self.pat=And(
Or(Word('D'),Word('E')),
More('F'),
Or(self,Word('G'))
)

wikidocs.net PDF, page : 326

classSlimp(MultiPattern):
'''slimp-Aand(Hor((BandslimpandC)or(slumpandC))'''
def__init__(self):
self.pat=And(
Word('A'),
Or(
Word('H'),
Or(
And(Word('B'),self,Word('C')),
And(Slump(),Word('C'))
)
)
)

classSlurpy(MultiPattern):
'''slurpy(slimpandslump)'''
def__init__(self):
self.pat=And(Slimp(),Slump())

defisSlurpy(target):
pat=Slurpy()
result=pat.match(target)
ifpat.remain():returnFalse
returnresult

###testcode##########################################################

classSlurpyTest(unittest.TestCase):
deftestWord(self):
word=Word('D')
self.assertEquals(True,word.match('DEF'))
self.assertEquals('EF',word.remain())
deftestAnd(self):
D=Word('D')

wikidocs.net PDF, page : 327

E=Word('E')
andDE=And(D,E)
self.assertEquals(True,andDE.match('DE'))
deftestMore(self):
self.assertEquals(True,More('F').match('FFFF'))
self.assertEquals(True,And(Word('D'),More('F')).match('DFFF'))
more=More('F')
more.match('FGHG')
self.assertEquals('GHG',more.remain())
deftestOr(self):
self.assertEquals(True,Or(Word('F'),Word('E')).match('F'))
self.assertEquals(True,Or(Word('F'),Word('E')).match('E'))
self.assertEquals(True,
And(More('K'),Or(Word('F'),Word('E'))).match('KKKKE'))
deftestSlump(self):
#Slumps:DFG,EFG,DFFFFFG,DFDFDFDFG,DFEFFFFFG
self.assertEquals(True,Slump().match('DFG'))
self.assertEquals(True,Slump().match('EFG'))
self.assertEquals(True,Slump().match('DFFFFFG'))
self.assertEquals(True,Slump().match('DFDFDFDFG'))
self.assertEquals(True,Slump().match('DFEFFFFFG'))
#NotSlumps:DFEFF,EFAHG,DEFG,DG,EFFFFDG
self.assertEquals(False,Slump().match('DFEFF'))
self.assertEquals(False,Slump().match('EFAHG'))
self.assertEquals(False,Slump().match('DEFG'))
self.assertEquals(False,Slump().match('DG'))
self.assertEquals(False,Slump().match('EFFFFDG'))
deftestSlimp(self):
#Slimps:AH,ABAHC,ABABAHCC,ADFGC,ADFFFFGC,ABAEFGCC,ADFDFGC
self.assertEquals(True,Slimp().match('AH'))
self.assertEquals(True,Slimp().match('ABAHC'))
self.assertEquals(True,Slimp().match('ABABAHCC'))
self.assertEquals(True,Slimp().match('ADFGC'))
self.assertEquals(True,Slimp().match('ADFFFFGC'))
self.assertEquals(True,Slimp().match('ABAEFGCC'))
self.assertEquals(True,Slimp().match('ADFDFGC'))
#NotSlimps:ABC,ABAH,DFGC,ABABAHC,SLIMP,ADGC
self.assertEquals(False,Slimp().match('ABC'))
self.assertEquals(False,Slimp().match('ABAH'))
self.assertEquals(False,Slimp().match('DFGC'))

wikidocs.net PDF, page : 328

self.assertEquals(False,Slimp().match('ABABAHC'))
self.assertEquals(False,Slimp().match('SLIMP'))
self.assertEquals(False,Slimp().match('ADGC'))
deftestSlurpy(self):
#Slurpys:AHDFG,ADFGCDFFFFFG,ABAEFGCCDFEFFFFFG
self.assertEquals(True,isSlurpy('AHDFG'))
self.assertEquals(True,isSlurpy('ADFGCDFFFFFG'))
self.assertEquals(True,isSlurpy('ABAEFGCCDFEFFFFFG'))
#NotSlurpys:AHDFGA,DFGAH,ABABCC
self.assertEquals(False,isSlurpy('AHDFGA'))
self.assertEquals(False,isSlurpy('DFGAH'))
self.assertEquals(False,isSlurpy('ABABCC'))

importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(SlurpyTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

wikidocs.net PDF, page : 329

[07] Eight Queen


Eight Queen Problem
Queen .
8 X 8 8 Queen . Queen
. ( Queen , Queen .)
. (X Queen .)

X
O
O
O
O
O
O
O

O
O
O
O
X
O
O
O

O
O
O
O
O
O
O
X

O
O
O
O
O
X
O
O

O
O
X
O
O
O
O
O

O
O
O
O
O
O
X
O

O
X
O
O
O
O
O
O

O
O
O
X
O
O
O
O

O
O
O
O
O
X
O
O

O
O
X
O
O
O
O
O

O
O
O
O
O
O
X
O

O
X
O
O
O
O
O
O

O
O
O
X
O
O
O
O

O
O
O
O
O
O
O
X

X
O
O
O
O
O
O
O

O
O
O
O
X
O
O
O

XX. .

[]

importunittest
count=0
classBoard:
def__init__(self,row,col):
self.row=row
self.col=col

wikidocs.net PDF, page : 330

self.map={}
forrinrange(self.row):
forcinrange(self.col):
self.map[r,c]='O'
defisQueenAvailable(self,point):
ifself.isQueenExistAtLine(point):returnFalse
ifself.isQueenExistAtDiagonal(point):returnFalse
returnTrue
defsetQueen(self,point):
self.map[point]='X'
defisExistQueen(self,point):
returnself.map[point]=='X'
defisQueenExistAtLine(self,point):
forcinrange(self.col):
ifself.isExistQueen((point[0],c)):returnTrue
forrinrange(self.row):
ifself.isExistQueen((r,point[1])):returnTrue
returnFalse
defisQueenExistAtDiagonal(self,point):
ifself.isQueenExistAtDiagonalLeftUp(point):returnTrue
ifself.isQueenExistAtDiagonalRightUp(point):returnTrue
returnFalse
defgetStartForDiagonalSearchLeftUp(self,(row,col)):
while1:
ifrow==0orcol==0:break
row=row-1
col=col-1
returnrow,col
defgetStartForDiagonalSearchRightUp(self,(row,col)):
while1:
ifrow==0orcol==self.col-1:break
row=row-1
col=col+1
returnrow,col
defisQueenExistAtDiagonalLeftUp(self,point):
startRow,startCol=self.getStartForDiagonalSearchLeftUp(point)
foriinrange(8):
r=startRow+i
c=startCol+i
ifr==self.row:break
ifc>=self.col:break
ifself.isExistQueen((r,c)):returnTrue
returnFalse
defisQueenExistAtDiagonalRightUp(self,point):

wikidocs.net PDF, page : 331

startRow,startCol=self.getStartForDiagonalSearchRightUp(point)
foriinrange(8):
r=startRow+i
c=startCol-i
ifr==self.row:break
ifc<0:break
ifself.isExistQueen((r,c)):returnTrue
returnFalse
defsearchNext(self,(row,col)):
forcinrange(col,self.col):
ifself.isQueenAvailable((row,c)):
self.copyAndRerun((row,c))
defrun(self):
forrinrange(0,self.row):
forcinrange(0,self.col):
ifself.isQueenAvailable((r,c)):
self.searchNext((r,c+1))
self.setQueen((r,c))
self.printEightQueen()
defprintEightQueen(self):
ifself.map.values().count('X')==self.row:
globalcount
count+=1
printcount
printself
defcopyAndRerun(self,nextPoint):
other=Board(self.row,self.col)
other.map=self.map.copy()
other.setQueen(nextPoint)
other.run()
def__str__(self):
result=[]
forrinrange(self.row):
forcinrange(self.col):
result.append("%2s"%self.map[r,c])
result.append('\n')
return''.join(result)

classEightQueenTest(unittest.TestCase):
deftestSetQueen(self):
bd=Board(8,8)
bd.setQueen((0,0))
self.failUnless(bd.isExistQueen((0,0)))

wikidocs.net PDF, page : 332

defassertCantSet(self,bd,point):
self.failIf(bd.isQueenAvailable(point))
defassertSet(self,bd,point):
self.failUnless(bd.isQueenAvailable(point))
deftestLineSet(self):
bd=Board(8,8)
bd.setQueen((0,0))
self.assertCantSet(bd,(0,1))
self.assertCantSet(bd,(1,0))
deftestDiagonalSetLeftUp(self):
bd=Board(8,8)
bd.setQueen((4,4))
self.assertCantSet(bd,(1,1))
self.assertCantSet(bd,(7,7))
self.assertCantSet(bd,(3,5))
self.assertCantSet(bd,(5,3))
deftestDiagonalSetRightUp(self):
bd=Board(8,8)
bd.setQueen((2,3))
self.assertCantSet(bd,(0,1))
self.assertCantSet(bd,(5,6))
self.assertCantSet(bd,(0,5))
self.assertCantSet(bd,(5,0))
deftestNormalSet(self):
bd=Board(8,8)
self.assertSet(bd,(0,0))
self.assertSet(bd,(1,2))
self.assertSet(bd,(2,6))
deftestRun(self):
bd=Board(8,8)
bd.run()

importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(EightQueenTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

wikidocs.net PDF, page : 333

[08] Tug Of War


About TugOfWar
.
. ,
. .

Input

, .

n .
n . 1 450
. 100.

output

,
. ,
. .

Sample Input

wikidocs.net PDF, page : 334

3
100
90
200

6
45
55
70
60
50
75

4
92
56
47
82

5
2
3
4
7
8

wikidocs.net PDF, page : 335

4
50
50
100
200

Sample Output

190 200

175 180

138 139

12 12

150 250

worst case 100 . 1 450 .

80

434

253

166

441
102

wikidocs.net PDF, page : 336

356
107
144
93
380
387
14
302
330
1
298
262
154
184
362
381
231
76
52
84
115
135
153
129
359
438
131
394
427
213
321
276
256
24
79
175
418
150
415
387
143
38
252
222

wikidocs.net PDF, page : 337

326
331
147
78
378
232
17
228
316
360
140
178
301
384
239
78
286
77
385
420
51
88
428
371
217
206
267
133
140
267
25
438
442
10
217
300
127
280
88
149
244
89
330
405

wikidocs.net PDF, page : 338

140
149
26
134
384
435

TugOfWar ( ) 10 .

worst case output

11402 11403

[]

.

. .
.

importunittest
classTeam:
def__init__(self,weights):
self.weights=weights
defsumOfWeight(self):
returnsum(self.weights)
defpull(self,index):
returnself.weights.pop(index)
defpush(self,weight):
self.weights.append(weight)
def__str__(self):
return"Sum:[%d]==>%s"%(self.sumOfWeight(),str(self.weights))

wikidocs.net PDF, page : 339

classJudge:
def__init__(self,blue,red):
self.blue=blueself.red=red
defchangeWeight(self,blueIndex,redIndex):
blueWeight=self.blue.pull(blueIndex)
redWeight=self.red.pull(redIndex)
self.blue.push(redWeight)
self.red.push(blueWeight)
defforBestBalance(self):
currentGap=abs(self.blue.sumOfWeight()-self.red.sumOfWeight())
minGap=450*len(self.blue.weights)
found=False
blueSum=self.blue.sumOfWeight()
redSum=self.red.sumOfWeight()
forblueIndex,blueWeightinenumerate(self.blue.weights):
forredIndex,redWeightinenumerate(self.red.weights):
gap=blueWeight-redWeight
nextGap=abs((blueSum-gap)-(redSum+gap))
ifnextGap<currentGapandnextGap<minGap:
minGap=nextGap
found=True
foundBlueIndex=blueIndex
foundRedIndex=redIndex
iffound:returnfoundBlueIndex,foundRedIndex
defmakeBalacedTeam(self):
count=0
whileTrue:
foundIndex=self.forBestBalance()
iffoundIndex:
blueIndex,redIndex=foundIndex
self.changeWeight(blueIndex,redIndex)
count+=1
#print"count:%d,gap:%d"%(count,
#abs(self.blue.sumOfWeight()-self.red.sumOfWeight()))
else:
break

deftugOfWar(data):
all=map(int,data.split())
half=len(all)/2
blue,red=Team(all[:half]),Team(all[half:])
Judge(blue,red).makeBalacedTeam()
result=[]

wikidocs.net PDF, page : 340

result.append('*'*78)
result.append(str(all))
result.append('-'*78)
result.append(str(blue))
result.append(str(red))
result.append('*'*78)
print
print'\n'.join(result)
importrandom
classTugWarTest(unittest.TestCase):
deftestTeam(self):
A=Team([1,2,3])
self.assertEquals(6,A.sumOfWeight())
self.assertEquals(1,A.pull(0))
self.assertEquals(5,A.sumOfWeight())
deftestJudge(self):
A=Team([1,2,3])
B=Team([4,5,6])
judge=Judge(A,B)
judge.changeWeight(1,0)
self.assertEquals([1,3,4],A.weights)
self.assertEquals([5,6,2],B.weights)
deftestJudgeforBestBalance(self):
blue=Team([1,2,3])
red=Team([4,5,6])
judge=Judge(blue,red)
self.assertEquals((0,1),judge.forBestBalance())
judge.changeWeight(0,1)
self.assertEquals(10,blue.sumOfWeight())
self.assertEquals(11,red.sumOfWeight())
deftestJudgeUntilBalance(self):
blue=Team([1,2,3])
red=Team([4,5,6])
judge=Judge(blue,red)
judge.makeBalacedTeam()
self.assertEquals([2,3,5],blue.weights)
self.assertEquals([4,6,1],red.weights)
defgetRandomData(self,n):
return''.join([str(random.randint(1,450))foriinrange(n)])
deftestTugOfWar(self):
tugOfWar("""123456""")
tugOfWar("""10090200""")
tugOfWar("""455570605075""")

wikidocs.net PDF, page : 341

tugOfWar("""92564782""")
tugOfWar("""23478""")
tugOfWar("""5050100200""")
tugOfWar(self.getRandomData(100))
#tugOfWar(self.getRandomData(500))
#tugOfWar(self.getRandomData(1000))
importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(TugWarTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

wikidocs.net PDF, page : 342

[09] LCD Display


LCD Display
.
. LCD
. LCD
.

.
s n n ( 0<= n <=
99,999,999 ),s ( 1<= s < 10 ) .0
.

'-' , '|'
LCD . s+2 ,
2s+3 .
.
.

.
.

2 12345

3 67890

wikidocs.net PDF, page : 343

|
|

-|
|
--

-|| ||
|| ||
-- -||
| |
||
| |
-- --

--

-|
|
--

--- --- --- --- --|


|| || || |
|
|| || || |
|
|| || || |
----- --| | || | || |
| | || | || |
| | || | || |
----- --- ---

[]

importunittest
classNumber:
@staticmethod

wikidocs.net PDF, page : 344

defget(num):
info={
0:['U','D','LU','LD','RU','RD'],
1:['RU','RD'],
2:['U','C','D','LD','RU'],
3:['U','C','D','RU','RD'],
4:['C','LU','RU','RD'],
5:['U','C','D','LU','RD'],
6:['U','C','D','LU','LD','RD'],
7:['U','RU','RD'],
8:['U','C','D','LU','LD','RU','RD'],
9:['U','C','D','LU','RU','RD']
}
returnNumber(info[num])
def__init__(self,info):
self.info=info
defhasValue(self,value):
returnself.info.count(value)
classLcd:
def__init__(self):
self.numbers=[]
self.result=[]
defadd(self,number):
self.numbers.append(number)
definit(self,*numbers):
fornumberinnumbers:
self.add(Number.get(number))
defmakeHorizon(self,zoom,C):
fornumberinself.numbers:
self.result.append('')
ifnumber.hasValue(C):self.result.append('-'*zoom)
else:self.result.append(''*zoom)
self.result.append(''*2)
self.result.append('\n')
defmakeVertical(self,zoom,L,R):
foriinrange(zoom):
fornumberinself.numbers:
ifnumber.hasValue(L):self.result.append('|')
else:self.result.append('')
self.result.append(''*zoom)
ifnumber.hasValue(R):self.result.append('|')
else:self.result.append('')
self.result.append('\n')

wikidocs.net PDF, page : 345

defmake(self,zoom):
self.makeHorizon(zoom,'U')
self.makeVertical(zoom,'LU','RU')
self.makeHorizon(zoom,'C')
self.makeVertical(zoom,'LD','RD')
self.makeHorizon(zoom,'D')
defgetResult(self):
return''.join(self.result)[:-1]

classLcdTest(unittest.TestCase):
deftestNormal(self):
lcd=Lcd()
lcd.add(Number.get(8))
lcd.make(1)
expect="""
||
||
"""
self.assertEquals(expect[1:-1],lcd.getResult())
deftestZoom(self):
lcd=Lcd()
lcd.add(Number.get(8))
lcd.make(2)
expect="""
-||
||
-||
||
-"""
self.assertEquals(expect[1:-1],lcd.getResult())
deftestAllNumberWithZoom(self):
lcd=Lcd()
lcd.init(1,2,3,4,5,6,7,8,9)
lcd.make(2)
print
printlcd.getResult()

wikidocs.net PDF, page : 346

importsys
suite=unittest.TestSuite()
suite.addTest(unittest.makeSuite(LcdTest))
unittest.TextTestRunner(verbosity=2,stream=sys.stdout).run(suite)

wikidocs.net PDF, page : 347

90.
?
.
. ,
.
www.python.org .
Swig, Zope, Jython, PIL, Numeric Python .



.
.




.
.

.
.

.


.
. .
.
.
.


http://www.python.org/doc/howto .
. .

Advocacy
,
.

Curses Programming with Python


Curses

wikidocs.net PDF, page : 348


Editor Configuration for Python
.

Regular Expression HOWTO


.

Socket Programming HOWTO


.

Sorting Mini-HOWTO
sort() .

XML HOWTO
XML

Why Python? Eric. S. Raymond


http://www2.linuxjournal.com/lj-issues/issue73/3882.html
,
.

Learning to Program - by Alan Gauld


http://www.crosswinds.net/~agauld/

. .

Non-Programmers Tutorial - Josh Cogliati


http://www.honors.montana.edu/~jjc/easytut/easytut/
.

wikidocs.net PDF, page : 349


Instant Python - by Magnus Lie Hetland
http://www.hetland.org/python/instant-python.php
.

Python for experienced programmers - Mark Pilgrim


http://diveintopython.org/toc.html

.

How to think like a computer scientist Python Version by Allen B.Downey and Jeffrey Elkner
http://www.ibiblio.org/obp/thinkCSpy/
.
.

comp.lang.python
, 100 .
.
.
. comp.lang.python .
URL comp.lang.python .
.
http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python

www.python.org
.
, . Topic Guide
Tkinter, XML, Databases, Web Programming SIGs(Special Interest
Groups)
, .

(python.kr)
.
.
.

wikidocs.net PDF, page : 350


?
.
.
, VI
.
.

.

(Edit Plus)
.
.
http://www.editplus.com/kr

URL .
.
. " .
.

1.
.
. .

wikidocs.net PDF, page : 351

.
==> "Python" .
python
.
.
. .
.

2.
.
Syntax . Syntax .
http://www.editplus.com/kr/javacpp.html

pythonfiles.zip . python.stx
. C:\Program Files\EditPlus 2( EditPlus 3)
. Syntax
. .

wikidocs.net PDF, page : 352

Syntax .
Python" . 'py' . (N)
Python Syntax C:\Program Files\EditPlus 2\python.stx
. ... .
. .
.
.

test.py Ctrl-1
.


Guido van Rossum. ( )

Python Java, JavaScript, Perl, Tcl Samlltalk .


C++, Common Lisp Scheme .
. . ,

wikidocs.net PDF, page : 353

(, , )
. , .

Java ()
Python Java . Python
. Python Java 3-5 .
Python .
, Python ,
Python (polymorphic list)
Python . Python
Java . , a+b ,
a b .
. (overloaded) . ,
Java , . a b , +
.
, Python '' , Java
. . Java (components)
Python ; Python Java .
, Java Python (implementation) .
Java Python . , Python Java
(Python ).

Javascript ()
Python '' JavaScript . JavaScript ( Java
), Python ,
. JavaScript . Python, ,

.

Perl ()
Python Perl ( ).
. . Perl
(: , ), Python
( ) .
(elegant) . ,
Python Perl . Python Perl
.

Tcl ()
Python Tcl , (extension language)
. , Tcl Python

wikidocs.net PDF, page : 354

. Tcl (name space) ,


. Tcl
C C++ . Python
' Python' . Python C C++
. Tcl Tk . Python Tk GUI
.
Tcl 8.0 ,
.

Smalltalk ()
Python Smalltalk Python '(mainstream)'
. Python Smalltalk (binding) . Python
. , Python ,
. Smalltalk
, Python WWW (email, HTML, FTP)
.
Python . Smalltalk
' ' , Python
. , GUI
, GUI Python .

C++
Java C++ . Python Java 3-5 ,
C++ 5-10 !! Python C++ 1
. Python C++
.

Common Lisp and Scheme


Python .
: Lisp ? Python Lisp
(capabilities) , Python
. , : Common Lisp
( ). Scheme .
Python , , . Scheme Moshe
Zadka Python vs. Scheme .

wikidocs.net PDF, page : 355

01. 3.0
: http://bluekyu.textcube.com/111
: Bluekyu

** 3
. .

1. PEP 3105 : Print Is A Function


Print . .

print([object,...],*,sep='',end='\n',file=sys.stdout)

print "Hello, Python.", "I like Python" 3.0


print("Hello, Python.", "I like Python") . sep
. ' ' Hello,
Python. I like Python sep='' Hello, Python.I like Python
. print
sep .

print "softspace" .(softspace print


.)

2. Views And Iterators Instead Of Lists


API . , dict.keys(),
dict,itmes(), dict,values() views . k = d.keys(), k.sort()
. k = sorted(d) .

views , .
a = {'one' : 1, 'two' : 2} , b = a.keys() a
b . views (iterated)
, . dict.iterkeys() dict.iteritmes(), dict.itervalues()
. keys items, values
views iter() . , map() filter()
. list() .
range() xrange()
. xrange() . zip()

wikidocs.net PDF, page : 356

3. Ordering Comparisons
3.0 . (<, >, <=, >=)
TypeError . 1 < 'a', 0 < None
False 3.0 .
. , = !=
.
sorted() list.sort() cmp . key
. key reverse . cmp
__cmp__() . __lt__(), __eq__(), __hash__()
. cmp() (a > b) - (a < b)
cmp() .

4. Integers
long int . , int .
long . , 1/2 . ,
1//2 .
sys.maxint . sys.maxsize sys.maxint
. long repr() long
L . 8 0123 0o123
.

5. Text Vs. Date Instead Of Unicode Vs. 8-bit


1) 3.0 .
. (, .) str
, . ,
.
http://diveintopython3.org/strings.html#byte-arrays

2) 2
TypeError . 2 8 8
8
UnicodeDecodeError .

3) u'...' .
b'...' .

4) ,

wikidocs.net PDF, page : 357

str.encode() bytes(s, encoding = ...) ,


bytes.decode() str(b, encoding=...) .

5) . , bytearray
. bytes API bytearray
. API collections.MutableSequence .

6) raw . ur'\u20ac'
3 r'\u20ac' 6 . , '\u20ac'
.

7) 2.3 basestring . str . 2to3


str .
(basestring 2
.)

8) () ()
. b
. , I/O
. , . (
2() .
.)
. (
( ) UTF-8 ,
.) codecs
.

9) .
. ,
API(open() os ) . API
. , os.listdir()
. , os.listdir()
UnicodeError .

10) os.environ sys.argv API ,


.
.

11) PEP 3138


repr escape .

wikidocs.net PDF, page : 358

control character code points escape . , repr('')


"''" "'\\xxx\\xxx\\xxx\\xxx'" .
"''" . , '\n' "'\\n'" .

12) PEP 3120, PEP 3131


UTF-8 . . ,
. (However, the standard library remains ASCII-only
with the exception of contributor names in comments.)

13) StringIO cStringIO . , io io.StringIO


io.BytesIO .

6. Overview Of Syntax Changes


< >
1) , PEP 3107 . .

deffoo(a:expression,b:expression=5)->expression:
...

: expression , -> expression


.
( expression 1+2
.)
__annotations__ . ,
__annotations__
. ,
.
2) PEP 3102 .
.

deff(a,b,c=key):
...

, c , c (*args)
. , ,
. ,
* .

wikidocs.net PDF, page : 359

deff(a,b,*,c=key):
...

3) PEP 3104 . nonlocal () .


.

>>>defbank_account1(initial_balance):
balance=initial_balance
defdeposit(amount):
balance=balance+amount
returnbalance
defwithdraw(amount):
balance=balance-amount
returnbalance
returndeposit,withdraw
>>>d,w=bank_account1(100)
>>>print(d(100))

, balance = balance + amount . balance


,
. balance
. nonlocal .

>>>defbank_account1(initial_balance):
balance=initial_balance
defdeposit(amount):
nonlocalbalance
balance=balance+amount
returnbalance
defwithdraw(amount):
nonlocalbalance
balance=balance-amount
returnbalance
returndeposit,withdraw
>>>d,w=bank_account1(100)
>>>print(d(100))
200

wikidocs.net PDF, page : 360

nonlocal balance balance


.
4) PEP 3132 . .
*arg
.

a,*rest,b=range(5)

3 . a=0, rest=[1,2,3], b=4


.
5) PEP 0274 . .
.

{k:vfork,vinstuff}

dict(stuff) , PEP
.
6) set . set(['a', 'b'])
3 {'a', 'b'} . , {} .
set set() . , set . , {x for x in
stuff} . set(stuff) .
7) 8 . 0o720 0720 .
2.6 .
8) 2 . 0b1010 bin() .
2.6 .
9) . b'...' B'...' ,
bytes() .

< >
1) PEP 3109, PEP 3134 . raise .
.
2) as with .
3) True False, None .

wikidocs.net PDF, page : 361

4) PEP 3110. except exc, var except exc as var .


.
5) PEP 3115. .

classC:
__metaclass__=M
...

classC(metaclass=M):
...

. __metaclass__ .
6) [... for var in item1, item2, ...] .
[... for var in (item1, item2, ...)] .
(semantics) . . ,
surrounding scope loop control .
7) (ellipsis) (...) .
. ... , . . .
.( .)

< >
1) PEP 3113. . def foo(a, (b, c)) : ...
, def foo(a, b_c) : b, c = b_c ... .
.
2) backtick (`) . repr .
3) <> . != .
4) exec . . , exec() stream
. print 1 f ,
exec f print 1 ,
exec(f.read()) .
5) l, L, u, U .
6) from (module) import * .
. , from (module) import (name) .

wikidocs.net PDF, page : 362

7) from .[module] import name . (.)


.(2.5
.)
8) Classic Class .

7. Changes Already Present In Python 2.6


2.6 .
1) PEP 343 : The 'with' statement
with . __future__ .
2.5 http://bluekyu.textcube.com/108 .
2) PEP 366 : Explicit Relative Imports From a Main Module
-m .
.
__package__ . , __name__
.
3) PEP 370 : Per-user site-packages Directory
site-packages .
site-packages ,
. site-packages 3rd .
site-packages dist-packages . (
. site.py
dist-packages .)
. Unix Mac ~/.local/ ,
%APPDATA%/Python . unix, mac lib/python2.6/site-packages
, Python26/site-packages .
PYTHONUSERBASE , -s
. (-S site-packages
.)
site.py site-packages .
site.py .
4) PEP 371 : The multiprocessing Package
multiprocessing .
. threading . .
5) PEP 3101 : Advanced String Formatting
. str.format() %
3.2 . 2.6 3 str
str bytes .

wikidocs.net PDF, page : 363

.
http://bluekyu.textcube.com/136

6) PEP 3105 : print As a Function


.
7) PEP 3110 : Exception-Handling Changes
, .
8) PEP 3112 : Byte Literals
, C .
.
9) PEP 3116 : New I/O Library
io . sys.stdin, sys.stdout, sys.stderr
io.TextIOBase . open() io.open()
. mode IOError ValueError
. .
10) PEP 3118 : Revised Buffer Protocol
buffer() , memorryview() .
.
11) PEP 3119 : Abstract Base Classes
, . .
12) PEP 3127 : Integer Literal Support and Syntax
.
13) PEP 3129 : Class Decorators
.
14) PEP 3141 : A Type Hierarchy for Numbers
. ABC
. ABC Number . Complex Number . Real
Complex . Rational Real . Integer Rational
. fractions .
.

8. Library Changes
. .
PEP 3108 .
1) md5 sha hashlib .

wikidocs.net PDF, page : 364

2) cPickle _pickle .

3) StringIO cStringIO io .

4) .
< dbm >
Current Name Replacement Name
anydbm dbm.__init__
dbhash dbm.bsd
dbm dbm.ndbm
dumbdm dbm.dumb
gdbm dbm.gnu
whichdb dbm.__init__
< urllib >
Current Name Replacement Name
urllib2 urllib.request, urllib.error
urlparse urllib.parse
urllib urllib.parse, urllib.request, urllib.error
robotparser urllib.robotparser
< tkinter >
Current Name Replacement Name
Dialog tkinter.dialog
FileDialog tkinter.filedialog
FixTk tkinter._fix
ScrolledText tkinter.scrolledtext
SimpleDialog tkinter.simpledialog
Tix tkinter.tix
Tkconstants tkinter.constants
Tkdnd tkinter.dnd
Tkinter tkinter.__init__
tkColorChooser tkinter.colorchooser
tkCommonDialog tkinter.commondialog
tkFileDialog tkinter.filedialog
tkFont tkinter.font
tkMessageBox tkinter.messagebox
tkSimpleDialog tkinter.simpledialog
turtle tkinter.turtle
PEP 3108 .
1) sets . set .

wikidocs.net PDF, page : 365

2) sys . sys.exitfunc(), sys.exc_clear(), sys.exc_type, sys.exc_value,


sys.exc_traceback .

3) array.array . read(), write() , fromfile(), tofile()


. c b u .

4) operator . sequenceIncludes() isCallable() .

5) thread . acquire_lock() release_lock() , acquire()


release() .

6) random . jumpahead() .

7) new .

8) tmpfile os.tmpnam(), os.tempnam(), os.tmpfile() .

9) tokenize . (Main Entry Point)


generate_tokens tokenize.tokenize() .

10) string.letters string.lowercase, string.uppercase . ,


string.ascii_letters .

11) __builtin__ builtins . global


__builtins__ . builtin __builtins__ builtins
.

9. Changes To Exceptions
.
1) PEP 0352
BaseException . .
2) Exception . , BaseException SystemExit
KeyboardInterrup .
except Exception .

wikidocs.net PDF, page : 366

3) StandardError .
4) . args .
( p. 481 16
.)

print(a[0],a[0].__class__.__name__,id(a[0]))

5) PEP 3109
raise Exception, args raise Exception(args) .
traceback . , __traceback__
.
6) PEP 3110
except Exception, variable except Exception as variable . ,
. except variable
. ,

exceptEasN:
foo

exceptEasN:
try:
foo
finally:
N=None
delN


.
7) PEP 3134
. , (implicit)
, (explicit) . (2 ) except finally
.

wikidocs.net PDF, page : 367

>>>try:
...raiseException('first')
...except:
...raiseException('second')
...
Traceback(mostrecentcalllast):
File"<stdin>",line2,in<module>
Exception:first
Duringhandlingoftheaboveexception,anotherexceptionoccurred:
Traceback(mostrecentcalllast):
File"<stdin>",line4,in<module>
Exception:second

try , except , 2
except try . 3
, .

__context__ .
. raise EXCEPTION from CAUSE
,
exc = EXCEPTION
exc.__cause__ = CAUSE
raise exc
. , CAUSE EXCEPTION
__cause__ .

>>>try:
...1/0
...exceptExceptionasvar:
...raiseException('1/0isError!')fromvar
...
Traceback(mostrecentcalllast):
File"<stdin>",line2,in<module>
ZeroDivisionError:intdivisionormodulobyzero
Theaboveexceptionwasthedirectcauseofthefollowingexception:
Traceback(mostrecentcalllast):
File"<stdin>",line4,in<module>
Exception:1/0isError!

wikidocs.net PDF, page : 368

try , except var


. , 2
1 .
2 1 . ( IDLE
.)
8) PEP 3134
traceback __traceback__ . traceback
sys.exc_traceback sys.exc_info()[2]
__traceback__ . .

defdo_logged(file,work):
try:
work()
exceptException,exc:
write_exception(file,exc)
raiseexc
fromtracebackimportformat_tb
defwrite_exception(file,exc):
...
type=exc.__class__
message=str(exc)
lines=format_tb(exc.__traceback__)
file.write(...type...message...lines...)
...

9) , .

10. Miscellaneous Other Changes


< Operators And Special Methods >
1) == NotImplemented , != == .

2) (unbound methods) .
.

3) __getslice__(), __setslice__(), __delslice__() . a[i:j]


a.__getitem__(slice(i, j)) . , __setitem__()
__delitem__() .

wikidocs.net PDF, page : 369

4) PEP 3114. next() __next__() . ,


. a.next()
next(a) .

5) __oct__() __hex__() . , oct() hex() __index__()


.

6) __members__ __methods__ .

7) func_X __X__ . ,
.

8) __nonzero__() __bool__() .

< Builtins >


1) PEP 3135. super() .
,
. , super() .

2) PEP 3111. raw_input() input() . , input() sys.stdin


(newline) . (prematurely)
EOFError . input() eval(input())
.

3) __next__() next() .

4) intern() sys.intern() .

5) apply() . , apply(f, args) f(*args) .

6) callable() . callable(f) isinstance(f, collections.Callable)


. operator.isCallable() .

7) coerce() . classic
.

8) execfile() . execfile(fn) exec(open(fn).read()) .

wikidocs.net PDF, page : 370

9) file . open() . io open


(stream) .

10) reduce() . functools.reduce() . ( "


, 99% for " .)

11) reload() . , imp.reload() .

12) dict.has_key() . , in .

11. Build and C API Changes


.
.
3 . , ABC
.
http://www.ibm.com/developerworks/kr/library/l-python3-1/
http://www.ibm.com/developerworks/kr/library/l-python3-2/

, 3 2.5 10% ...........


(int) .
. ^^

wikidocs.net PDF, page : 371

99.
.
-doolyes

. TDD... . By. Mr. Lonley.

. Python .
.
.^^ - ItsMe

^*^

3.0 ....

Pythone , .. ^^)
.

python .^^;
.

.
. ( ^^;)
XML C
. ,
scope, call by reference, call by value , id()
=> ID , sys.getrefcount()
. ^^
. -2009.04.01 (-_-; ......) .

wikidocs.net PDF, page : 372


. . 2009.04.12 by
Robinson

3.0

. . by Lak

. by simon

C . . 3.0
.

( ) .
. :) 10.01.15 by

wikidocs.net PDF, page : 373

You might also like