SlideShare a Scribd company logo
1 of 23
³æ¦æµù¸Ñ
>>> #print ('§Ú³Qµù¸Ñ¤F~')
>>> print ('§Ú¨S³Qµù¸Ñ¡I')
>>> # print ('§Ú¤S³Qµù¸Ñ¤F!!')
>>> print ('ǢǢǢǢ')
§Ú¨S³Qµù¸Ñ¡I «¢«¢«¢«¢
¦h¦æµù¸Ñ¡G¥Î ''' ¥]¦í·Qnµù¸Ñªº¤º®e
>>> n = 9
>>> m = 10
>>> ''' print( '±q³o¦æ¶}©l" )
>>> n = 0
>>> m = 1
>>> print( '¤@ª½µù¸Ñ¨ì³oÃä' ) '''
>>> print ( n, m )
9 10
python ¤¤¥i¥Hª½±µ§Q¥Î²Å¸¹¨ÓÀx¦s¼ÆÈ¡A¦r¦ê©Î¸ê®Æµ²ºc¡A¤]´N¬O§Ú-
̩ҿתºÅܼơA·íÅܼƦs©ñ¸ê®Æ«á¡A´N¥i¥Hª½±µ®³¨Ó¹Bºâ©Î§@¨ä¥¦³B²z¡A¤£¥²¶i¦æ«Å§i¡C
>>> x=6
>>> print x
6
>>> print x+2
8
>>> y='abc'
>>> print y+'def'
abcdef
>>> y=y+'def'
>>> print y
abcdef
>>> z=2.3
>>> print z+x
8.3
python ªº¼Æȸê®Æ«¬ºA¦³¤TºØ¡G¾ã¼Æ(integer)¡B¯BÂI¼Æ(float)¤Î½Æ¼Æ(complex number)¡C
¾ã¼Æ¤Î¯BÂI¼Æ¥i¥Hª½±µ¶i¦æ¥|«h¹Bºâ¡B¾l¼Æ¹Bºâ¤Î«ü¼Æ¹Bºâ¡A¨t²Î·|¦Û°ÊÂà
´«¬°½d³ò¤jªº«¬ºA¡C
>>> 10+2
12
>>> 4.5+6
10.5
>>> 2**3
8
>>> 2^5
7
>>> 2.5/5
0.5
>>> 16**0.25
2.0
°£ªk¹Bºâ«h¨Ì·Ó±z©Ònªºµ²ªG¨Ó°Ï¤À¬°¾ã¼Æ°£ªk»P¯BÂI¼Æ°£ªk¡C
Y°£¼Æ»P³Q°£¼Æ¬Ò¬°¾ã¼Æ®É¡A©Ò±o¨ìªºµ²ªG¥u¦³°Óªº¾ã¼Æ³¡¥÷¡C
Y°£¼Æ©Î³Q°£¼Æ¨ä¤¤¤@Ó¬°¯BÂI¼Æ®É¡A©Ò±o¨ìªºµ²ªG´N·|¬O±a¦³¤p¼Æ§¹¾ãªº°Ó¡C
>>> 3/2
1
>>> 3.0/2
1.5
>>> 3/2.0
1.5
>>> 10.0/3
3.3333333333333335
¹ï©ó¯BÂI¼Æ¦Ó¨¥¡A¦]¼Æȧe²{¦ì¼Æ¦³¡Aªí¥Üªk·|±N³¡¥÷¦ì¼Æ±Ë¥h¡A³y¦¨Åã¥Ü¤W·|
¦³»~®t¡A·U¤j¶q¹Bºâ»~®t·|·U¤j¡A¦ý¹ï©ó¹ê»Úµ²ªGÅã¥Ü¤W¥i¥H§Q¥ÎÂà
´«¬°¾ã¼Æint()©Î¨ú¯BÂI¼Æ¦³®Ä¦ì¼Æround()¨Ó¸Ñ¨M³oÓ°ÝÃD¡A¦p¡G
>>> x=0.1
>>> print x
0.1
>>> x**10
1.0000000000000006e-10
>>> x**50
1.0000000000000027e-50
¾ã¼Æ»P¯BÂI¼ÆªºÂà´«¥i¥H§Q¥Îint( )»Pfloat( )¨âÓ¨ç¼Æ¨Ó§¹¦¨¡C
>>> x=4.9
>>> int(x)
4
>>> y=5
>>> float(y)
5.0
>>> z=float(y)/x
>>> z
1.0204081632653061
>>> round(z,5)
1.02041
¹ï©ó½Æ¼Æªº¸ê®Æ«¬ºA¡A¥i¥H¨Ï¥Î x+yj ©Î x+yJ ¨âºØ(j©ÎJ)¨Óªí¥Ü¡A¨ä¤
¤xªí¥Ü¹ê³¡¡Ayªí¥Üµê³¡¡C
>>> x=1+4j
>>> print x
(1+4j)
>>> y=2+3j
>>> y
(2+3j)
>>> x+y
(3+7j)
>>> x*y
(-10+11j)
>>> x+6
(7+4j)
>>> x**2
(-15+8j)
>>> y**2
(-5+12j)
Yn³æ¿W¨ú¥X½Æ¼Æªº¹ê³¡©Îµê³¡¡A¥i¥H¨Ï¥Îreal¤Îimag¨âÓÄÝ©Ê¡C
>>> x.real
1.0
>>> x.imag
4.0
python¤¤¦r¦ê¸ê®Æ¥i¥H¥Î¥b«¬ªº³æ¤Þ¸¹ ( ' )©ÎÂù¤Þ¸¹( " )¨Ó±N¦r¦ê¤º®e¥]ÂЦb¨ä¤¤
¡A¦pªG¦b¨ä¤¤¦³¥²nÅã¥Ü³æ¤Þ¸¹©ÎÂù¤Þ¸¹®É¡A¥i¥H¥Î(  )¸õ²æ¦r¤¸¨Ó±N³o¨â-
ӲŸ¹Åã¥Ü¥X¨Ó¡C
>>> x='Hello Eric'
>>> print x
Hello Eric
>>> x='Hello, I'm Eric'
>>> print x
Hello, I'm Eric
¦b°õ¦æÀô¹Ò¤¤¡AµLªk§Q¥ÎEnter¨Óª½±µ´«¦æ¡AYn¶i¦æ´«¦æ¡A¥i¥H¥Î( n )ªº¦r¤¸¨Ó¹F¦¨¡C
>>> x='Hello, n I'm Eric'
>>> print x
Hello,
I'm Eric
Y¦bµ{¦¡½X¤¤¤@¦¸n¿é¤J¦h¦æ®É¡A¥i¨Ï¥Î(  )²Å¸¹¨Ó¹F¦¨¡C
>>> x='Hello, 
... I'm Eric'
>>> print x
Hello, I'm Eric
¥t¥~¤]¥i¥H¨Ï¥Î¤TÓ³æ¤Þ¸¹( ''' )©ÎÂù¤Þ¸¹( """ )¨Ó§¹¾ã«O¯d¦r¦ê¸ê®Æªºì©l®æ¦¡¡C
>>> x='''Hello,
... I'm Eric'''
>>> x
"Hello,nI'm Eric"
>>> print x
Hello,
I'm Eric
¦r¦ê¥i¥H¥Î( + )¸¹©ÎªÅ¥Õ¨Ó¹F¨ì¦r¦êªº³sµ²§@¥Î¡A¥t¥~¥i¥H¥Î¼¸¹( * )¨Ó¹F¨ì¿¼Æªº§@¥Î
>>> x='Hello, '
>>> y='Eric'
>>> print x+y
Hello, Eric
>>> z='Hello, ' 'Eric'
>>> z
'Hello, Eric'
>>> print x*5+y*5
Hello, Hello, Hello, Hello, Hello, EricEricEricEricEric
¦ý¨âÓ¦r¦êÅܼƫh¤£¦æ¥ÎªÅ¥Õ¨Ó°µ²Õ¦X¹Bºâ¡A¥²¶·¥Î( + )ªº²Å¸¹¨Ó²Õ¦X¦b¤@°_¡A¥t¥~¦r¦êY-
n»P¨ä¥¦«D¦r¦ê«¬ºAªºÅܼƬۥ[¡A¥²¶·n¥ý±N«D¦r¦êªºÅܼƧQ¥Îstr( )¨ç¼ÆÂà
´«¬°¦r¦ê¦A¶i¦æ¹Bºâ¡C
>>> z=x y
File "<stdin>", line 1
z=x y
^
SyntaxError: invalid syntax
>>> z=x+y
>>> z
'Hello, Eric'
>>> i=9
>>> print i+x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> print str(i)+x
9Hello,
Yn¨ú¥X¦r¦ê¤¤¬Y¨Ç¦r¤¸¡A¥i¥H±N¦¹¦r¦êªº¨C¤@Ó¦r¤¸·í¦¨°}¦C¤¤ªº¤¸¯À¡A°_©lªº¦ì¸m¬°¢¯¡C
>>> z='Hello, Eric'
>>> z[3]
'l'
>>> z[0:4]
'Hell'
>>> z[:4]
'Hell'
>>> z[4:]
'o, Eric'
>>> z[-3]
'r'
>>> z[0:3]+z[5:]
'Hel, Eric'
npºâ¦r¦êªºªø«×¡A¥i¥Îlen( )¨ç¼Æ¨Ópºâ¡C
>>> z
'Hello, Eric'
>>> len(z)
11
¦r¦êªº©µ¦ù¤Á¤ù¹Bºâ¡A¥i¥H³z¹L²Ä¤TÓ¨îȨӨú¥X¬Û¹jµ¥¶Zªº¦r¦ê¦r¤¸¡C
>>> s='abcdefghijklmno'
>>> s[1:10:2]
'bdfhj'
python ¦r¦êªºUnicode½s½X
Unicode¡]¤¤
¤å¡G¸U°ê½X¡B°ê»Ú½X¡B²Î¤@½X¡B³æ¤@½X¡^¬O¹q¸£¬ì¾Ç»â°ì¸Ìªº¤@¶µ·~¬É¼Ð·Ç¡C¥¦¹ï¥@¬É¤W¤j
³¡¤Àªº¤å¦r¨t²Î¶i¦æ¤F¾ã²z¡B½s½X¡A¨Ï±o¹q¸£¥i¥H¥Î§ó¬°Â²³æªº¤è¦¡¨Ó§e²{©M³B²z¤å¦r¡C
¦bpython 2.7ª©¤¤¡A¹w³]ªº¦r¦ê®æ¦¡¬°ASCII½s½X¡A¦pªG-
n¥Hunicodeªº½s½X®æ¦¡¨ÓÀx¦s¦r¦ê¡A¥²¶·¦b¦r¦êªº³Ì«e±¥[¤W 'u' ªº«e¸m¦r¤¸¡A¦p¡G
>>> z='Hello, Eric'
>>> r=u'Hello, Eric'
>>> r
u'Hello, Eric'
>>> z
'Hello, Eric'
>>> chin=u'³o¬O¤@Ó¤¤¤å¦r¦ê'
>>> chin
u'u9019u662fu4e00u500bu4e2du6587u5b57u4e32'
>>> achin='³o¬O¤@Ó¤¤¤å¦r¦ê'
>>> achin
'xb3oxacOxa4@xadxd3xa4xa4xa4xe5xa6rxa6xea'
>>> print chin
³o¬O¤@Ó¤¤¤å¦r¦ê
>>> print achin
³o¬O¤@Ó¤¤¤å¦r¦ê
¹ïunicode½s½Xªº¦r¦ê¦Ó¨¥¡A¨ä«¬¦¡¦p¦P 'uXXXX'
ªº®æ¦¡¡A¦UºØ¯S®í²Å¸¹ªºunicode½s½X¡A¥i°Ñ¦Òhttp://www.tamasoft.co.jp/en/general-
info/unicode.html¡@¡C
>>> a=u'u0040'
>>> print a
@
python ªºList¸ê®Æ«¬ºA
List¸ê®Æ«¬ºA¥i¥H¥Î¨Óªí¥Ü¥ô¦ópython¸ê®Æ«¬ºAªº¦³§Ç¶°¦X¡A¥ç§Y±N¥ô¦ó¸ê®Æ«¬ºAªº¸ê®Æ¦ê
±µ¦b¤@°_¡A¥i¥H¬O¤£¦P¸ê®Æ«¬ºAªº²Õ¦X¡AList¤¤¤]¥i¥H¥]§t¥t¤@ÓList¡A·ín¨ú¥X¨ä¤
¤ªº¸ê®Æ®É¡A¥i¥H¥ÎÃþ¦ü°}¦Cªº¤è¦¡¡A«ü©wn¨ú¥X¦ì¸mªº¸ê®Æ©Î¤@Ó½d³òªº¸ê®Æ¡A¦p¡G
>>> lst=[1,2,'abc',3.4,5+6j]
>>> lst
[1, 2, 'abc', 3.4, (5+6j)]
>>> lst[4]
(5+6j)
>>> lst[3:]
[3.4, (5+6j)]
>>> lst[1:3]
[2, 'abc']
>>> lst[1:3]=[5,6]
>>> lst
[1, 5, 6, 3.4, (5+6j)]
List¥i¥H³z¹L( + )ªº²Å¸¹¨Ó²Õ¦X¨âÓ¤£¦PªºList¡A¦pªG¬On¥
[¨ì§ÀºÝ¡A«h¥i¥H§Q¥Îappend©Îextend¨âºØ¤èªk¨Ó¹F¦¨¡A¦ý¦¹¨âÓ¤èªk¬O¤£
¤@¼Ëªº¡A¥i°Ñ¦Ò¤U±¨Ò¤l¡A¤À¿ë¥¦Ìªº¤£¦P¡C
>>> x=[1,2,3]
>>> y=[4,5,6]
>>> z=[a,b,c]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> z=['a','b','c']
>>> x+y
[1, 2, 3, 4, 5, 6]
>>> x
[1, 2, 3]
>>> r=x+y
>>> r
[1, 2, 3, 4, 5, 6]
>>> x.append(y)
>>> x
[1, 2, 3, 'abc', [4, 5, 6]]
>>> x.extend(y)
>>> x
[1, 2, 3, 'abc', [4, 5, 6], 4, 5, 6]
Listªº±Æ§Ç¥i¥H¥Îreverse( )¨ç¼Æ©Î¬O.sort(reverse=True)¨Ó¹F¦¨
>>> x
[0, 1, 2, 3, 4, 5]
>>> x.sort(reverse=True)
>>> x
[5, 4, 3, 2, 1, 0]
>>> x
[5, 4, 3, 2, 1, 0]
>>> x.reverse()
>>> x
[0, 1, 2, 3, 4, 5]
List Comprehension¡@ªí¦C¸ÑªR¡A§ÚÌ¥i¥H§Q¥Îfor °j°é¨Ó?¦¨¡C
l=[x**2 for x in range(10)]
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
python ªºtuple¸ê®Æ«¬ºA
python ªºtuple¸ê®Æ«¬ºA»PList«D±`Ãþ¦ü¡A¬O¥Î¥ª¥k¨âÓ¬A¸¹ ' ( '»P ' ) '±N¤¸¯À¥]¦b¨ä¤
¤¡A¨ä»PList³Ì¤jªº®t§O¦b©ó¤@¦ý¨M©w¤F¤¸¯Àªº¤º®e¡A´N¤£¥i¥HÅܧó¡A¤
£¹³List¤@¼Ë¥i¥HÀH®Éקï¡C
>>> x=[1,2,3]
>>> y=(4,5,6)
>>> x[2]
3
>>> y[2]
6
>>> x
[1, 2, 3]
>>> x[2]=99
>>> x
[1, 2, 99]
>>> y[2]=99
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
pythonªºdict¸ê®Æ«¬ºA
¦bpythonªºListªº¸ê®Æ«¬ºA¤¤¡A¨CÓ¤¸¯À¥H¥¦©Ò¦bªº¦ì¸m§Ç¸¹§@¬°¯Á¤Þ-
Èindex¨Ó¶i¦æ¸ê®Æ¦s¨úªºkeyÈ¡A¦bdictªº¸ê®Æ«¬ºA¡A«h¬O¥i¥H¦Û©wkeyȨӰµ¬°¸ê®Æªº¯Á¤Þ-
È¡C
dict¸ê®Æ«¬ºA¬O¥Î¥ª¥k¤j¬A¸¹ ' { ' ¡B' } ' ±N¸ê®Æ¥]§t¦b¨ä¤¤¡A¨Ã¥Î³r¸¹ ' , '
¨Ó§@¬°°Ï¹j¡A¨CÓkey-value¬O¥H«_¸¹ ' : ' ¨Ó¶i¦æ°t¹ï¡A¦p¡G
>>> dic={'name':'eric','phone':'0900000000','email':'a@b.c.d'}
>>> dic
{'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'}
dict¸ê®Æ«¬ºAªºkeyȤ@©wn¬O¦r¦ê¸ê®Æ¡AvalueÈ«h¥i¥H¬O¥ô¦ó¸ê®Æ«¬ºA¡C
dict¤]¥i¥H¥ÑListªº°t¹ïtuple¸ê®ÆÂà´«¦Ó¨Ó¡A¨ä¤¤tuple²Ä¤@Ó¤¸¯À·|Âà´«¬°key¡A²Ä¤G-
Ó¤¸¯À·|Âà´«¦¨value
>>> x=[('name','eric'),('phone','0900000000'),('email','a@b.c.d')]
>>> y=dict(x)
>>> y
{'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'}
>>> y['phone']
'0900000000'
¥t¥~¤]¥i¥H¥Îzipªº¤è¦¡±N¨âÓ¦P¼Æ¶q¤£¦PListÂà´«¦¨¤@Ódict¸ê®Æ«¬ºA¡A¦p¡G
>>> x=['name','phone','email']
>>> y=['eric','0900000000','a@b.c.d']
>>> z=zip(x,y)
>>> z
[('name', 'eric'), ('phone', '0900000000'), ('email', 'a@b.c.d')]
>>> dict(z)
{'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'}
>>> z
[('name', 'eric'), ('phone', '0900000000'), ('email', 'a@b.c.d')]
>>> r=dict(z)
>>> r
{'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'}
¥t¥~¡A§Ṳ́]¥i¥H±NdictÂà´«¦¨Listªº¸ê®Æ«¬ºA¡C
>>> t=r.items()
>>> t
[('phone', '0900000000'), ('name', 'eric'), ('email', 'a@b.c.d')]
Y§ÚÌn¨ú¥Xdictªºkey©ÎvalueȮɡA¥i¥H¨Ï¥Îkeys( )¤Îvalues( )¨âÓ¤èªk¨Ó¨ú¥X¡A¦p
>>> r
{'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'}
>>> r.keys()
['phone', 'name', 'email']
>>> r.values()
['0900000000', 'eric', 'a@b.c.d']
Yn§R°£¬Y¤@¹ïkey-value²Õ¦X®É¡A¥i¥H¨Ï¥Îdel«ü¥O¡A¦p¡G
>>> r
{'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'}
>>> del r['name']
>>> r
{'phone': '0900000000', 'email': 'a@b.c.d'}
python ªº¥¬ªL¸ê®Æ«¬ºA»PªÅÈ
python ¤¤nªí¥Ü¥¬ªL¸ê®Æ«¬ºA¡A¥i¥H¨Ï¥ÎTrue¤ÎFalse¨Óªí¥Ü¡A¦b±±¨î¬yµ{¤¤¡A·|¨Ï¥Î¥¬ªL-
ȨӧPÂ_¬O§_¶i¤J°j°é¡C
>>> t=True
>>> type(t)
<type 'bool'>
>>> r=False
>>> r
False
Noneªí¥ÜÅܼƬOªÅÈ¡A¨ä¬Û·í©óJavaªºnull¡C
>>> x
['name', 'phone', 'email']
>>> x=None
>>> x
python ªº¬yµ{±±¨î
python ¦b°õ¦æµ{¦¡®É¡A³£¬O¨Ì·Óµ{¦¡½Xªº¶¶§Ç¥Ñ¤W¦Ó¤U°õ¦æ¡AY¹J¨ìµ{¦¡»Ýn°µ§PÂ_¡B©Î»Ý-
n¤ÏÂаõ¦æ¬Y´X¦æµ{¦¡½X®É¡A´N»Ýn§ïÅܵ{¦¡°õ¦æªº¬yµ{¡C
if ±ø¥ó§PÂ_¦¡
·í»Ýn°µ±ø¥ó§PÂ_®É¡A´N¥²¶·¨Ï¥Î if ªº±ø¥ó§PÂ_¡A¦p¡G
>>> x=30
>>> if x>30:
... print 'x is more than 30.'
>>> elif x==30:
... print 'x is equal to 30.'
>>> else:
... print 'x is small than 30.'
>>> ...
x is equal to 30.
if ªº±ø¥ó§PÂ_¥i·f°t elif ¤Î else ¨Ó§PÂ_¨ä¥¦ªº±ø¥ó¡C¨C¤@ӲŦX±ø¥óªº°Ï¶ô¥H "¡G"
¶}©l¡A¥i¥H¥ÎÁY±Æ¨Ó°Ï¤À¡A¦ý¦P¤@°Ï¬qªºÁY±Æ¤è¦¡n¤@P¡C
if / else ¤T¤¸¹Bºâ¦¡
>>> if X:
... A=Y
>>> else:
... A=Z
>>> x=1
>>> if x:
... a=2
... else:
... a=3
...
>>> a
2
>>> b=2 if x else 3
>>> b
2
>>> x=0
>>> b=2 if x else 3
>>> b
3
>>> if <±ø¥ó1 > :
... #±Ôz1
>>> elif < ±ø¥ó2 > :
... #±Ôz2
>>> else :
... #±Ôz
while °j°é
¦pªG§Æ±æ¤ÏÂаõ¦æ¬Y¤@¬qµ{¦¡½X¡Aª½¨ì¹F¦¨¬Y±ø¥ó«á¤~µ²§ô®É¡A¥i¥H¨Ï¥Î while °j°é¡C
>>> i=0
>>> while i<10:
... print i
... i+=1
...
0
1
2
3
4
5
6
7
8
9
for °j°é
¦pªGn°w¹ï¤@Ó list ªº¸ê®Æ½d³ò§@°j°é¡A¥i¥H¨Ï¥Îfor °j°é¡A·í¨C¦¸°õ¦æ®É¡A´N·|¨Ì§Ç±q
list ¤¤¨ú¥X¤@Ó¤¸¯À¨Ó³B²z¡C
>>> x=range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in x:
... print i
...
0
1
2
3
4
5
6
7
8
9
Y list ¤¤ªº¸ê®Æ¬O list ©Î tuple¸ê®Æ«¬ºA®É¡A¤]¥i¥H¨Ï¥Îfor
°j°é¨Ó¨ú¥X¹ïÀ³ªº¤¸¯À¡A¦p¡G
>>> dic={'name':'eric','email':'eric@gmail.com'}
>>> for k,v in dic.items():
... print 'dic[%s]=%s'%(k,v)
...
>>> dic[name]=eric
>>> dic[email]=eric@gmail.com
>>>
break?z·|¥ß§Y¸õÂ÷°j°é
while °j°é¥i¥H·f°tbreak ¨Ó¤¤Â_©Î©¿²¤¬Y¤@³¡¥÷ªºµ{¦¡°j°é¡C
>>> i=0
>>> while i<10:
... if i==5: break
... print i
... i+=1
...
0
1
2
3
4
continue?z·|¸õ¦Ü³Ìªñ©Ò¦bªº°j°é
§Y·í¦¸¤£°µ¡A¨Ó¨ì°j°é¶}ÀY¦C¡AÄ~Äò¤U¤@¦¸
>>> x=10
>>> while x:
... x-=1
... if x%2!=0: continue
... print x
...
8
6
4
2
0
pass ?z¬O¤°»ò¨Æ¤]¤£°µ¡AÄ~Äò°õ¦æ¤U¤@Ó?z¡C
>>> while 1:
... pass
...
n«öctrl-C¤~·|°±¤î¡C
try?z
·íµ{¦¡¦³¥i¯à°õ¦æ®É¥X²{¨Ò¥~¿ù»~¨Æ¥ó®É¡A§ÚÌ¥i¥H¨Ï¥Îtryªº±±¨î¶µ±Nµ{¦¡¥]§t¦b¨ä¤¤
¡A¨ä¥Îªk¦p¤U¡G¡@
>>> while True:
... reply=raw_input('Enter number:')
... if reply=='stop': break
... try:
... num=int(reply)
... except:
... print 'Bad!'*8
... else:
... print int(reply)**2
... print 'Bye'
°õ¦æµ²ªG¡G
python trySample.py
Enter number:8
64
Enter number:9
81
Enter number:ee
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
Enter number:i
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
Enter number:stop
Bye
example :
¦p¦ó¥Îfor¤Îif/elseªº§PÂ_¦¡¡A¼g¥X¤U¦C¹Ï¥Ü
*
***
*****
*******
*****
***
*
Ans:
>>> intMaxSize=7
... for i in range(1,intMaxSize*2+1,2):
... if i>intMaxSize: print '*'*(intMaxSize-(i-intMaxSize))
... else: print '*'*i
is ¥Îªk
>>> 'abc' is 'qoo'
False
is not ¥Îªk
>>> 'banana' is not 'apple'
True
in ¥Îªk
>>> 'a' in 'apple'
True
¯S®í¦r¤¸
d # ¼Æ¦r = [0-9]
D # «D¼Æ¦r =[ ^0-9 ]
s # ªÅ¥Õ¦r¤¸ = [ tnrfv]
S # «DªÅ¥Õ¦r¤¸ = [^ tnrfv]
w # ¦r¥À»P¼Æ¦r =[0-9a-zA-Z]
W # «D¦r¥À»P¼Æ¦r = [^0-9a-zA-Z]
µ{¦¡½d¨Ò1
# * = {0,} = 0~µL¦¸
>>> import re
>>> print(re.findall('ab*', '1add2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0~n
>>> print(re.findall('ab*', '1aabbbbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0~n
>>> print(re.findall('ab{0,}', '1babbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0~n
>>> print(re.findall('1[D]*', '1abc2')) # ´M§ä1¶}ÀY¡A«á-
±«D¼Æ¦rªø«×¬°0~n
>>> print(re.findall('1*c', '1abc2')) # ´M§ä1ªø«×¬°0~n¡A«á±¥X²{c
['a'] ['a', 'abbbbb'] ['abbb'] ['1abc'] ['c']
µ{¦¡½d¨Ò2
# + = {1,} = 1~µL¦¸
>>> import re
>>> print(re.findall('ab+', '1add2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°1~n
>>> print(re.findall('ab+', '1aab2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°1~n
>>> print(re.findall('ab{1,}', '1babbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°1~n
>>> print(re.findall('1[D]+', '1abc2')) # ´M§ä1¶}ÀY¡A«á-
±«D¼Æ¦rªø«×¬°0~n
>>> print(re.findall('w+', '1abc2')) # ´M§ä¦r¥À»P¼Æ¦r¡Aªø«×¬°1~n
>>> print(re.findall('[a-b1]+', '1abc2')) # ´M§ä¦r¥Àa-b©Î1¡Aªø«×¬°1~n
[] ['ab'] ['abbb'] ['1abc'] ['1abc2'] ['1ab']
µ{¦¡½d¨Ò3
# ? = {0,1} = 0©Î1¦¸
>>> import re
>>> print(re.findall('ab?', '1add2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0©Î1
>>> print(re.findall('ab?', '1aab2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0©Î1
>>> print(re.findall('ab?', '1babbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0©Î1
>>> print(re.findall('1[D]?', '1abc2')) # ´M§ä1¶}ÀY¡A«á-
±«D¼Æ¦rªø«×¬°0©Î1
>>> print(re.findall('[a-b]', '1abc2')) # ´M§äa©Îb
['a'] ['a', 'ab'] ['ab'] ['1a'] ['a', 'b']
µ{¦¡½d¨Ò4
# ^ = ¦r¦êªº¶}ÀY (¥Î¦b¤¤¬A¸¹¤ºªº¤~¬O "«D" [^ ])
>>> import re
>>> print(re.findall('^a', 'abc123')) # ¥Ha¬°¶}ÀYªº¦r
>>> print(re.findall('^1', 'abc123')) # ¥H1¬°¶}ÀYªº¦r
>>> print(re.findall('^D', 'abc123')) # «D¼Æ¦r¶}ÀYªº¦r
>>> print(re.findall('^[D]+', 'abc123')) # «D¼Æ¦r¶}ÀY¡Aªø«×¬°1~n¦¸
>>> print(re.findall('^w+', 'abc123')) #
¦r¥À©Î¼Æ¦r¶}ÀY¡Aªø«×¬°1~n¦¸
['a'] [] ['a'] ['abc'] ['abc123']
µ{¦¡½d¨Ò5
# $ = ¦r¦êªºµ²§À
>>> import re
>>> print(re.findall('1$', 'abc123')) # ¥H1µ²§Àªº¦r
>>> print(re.findall('3$', 'abc123')) # ¥H3µ²§Àªº¦r
>>> print(re.findall('d$', 'abc123')) # ¥H¼Æ¦rµ²§Àªº¦r
>>> print(re.findall('d+$', 'abc123')) # ¥H¼Æ¦rµ²§Àªº¦r¡Aªø«×¬°1~n
>>> print(re.findall('[w]+$', 'abc123')) # ¦r¥À©Î¼Æ¦rµ²§À¡Aªø«×¬°1~n
[] ['3'] ['3'] ['123'] ['abc123']
¨ç¦¡¡Gfindall() ´M§ä¥þ³¡
>>> import re
>>> text =
'shdfluihnlsdgjlsrfjileghluiesrgl3h42h3583593hu6i4h32896h3896h2436jl423j84936j23
l4jt4lfff9m39m39f'
>>> pwd = re.findall('d',text)
>>> print(pwd)
['3', '4', '2', '3', '5', '8', '3', '5', '9', '3', '6', '4', '3', '2', '8', '9',
'6', '3', '8', '9', '6', '2', '4', '3', '6', '4', '2', '3', '8', '4', '9', '3',
'6', '2', '3', '4', '4', '9', '3', '9', '3', '9']
python ¨ç¦¡³B²z
·í¦³¤@¬qµ{¦¡½X»Ýn«Âаõ¦æ®É¡A§ÚÌ¥i¥H±N¦¹¬qµ{¦¡½X©w¸q¦¨¤@Ө禡(function)
¡A¥H§Q§@¬°«áÄò©I¥s¨Ï¥Î¡C
¨ç¦¡ªº©w¸q
§ÚÌ¥i¥H³z¹Ldef ªº¤è¦¡¨Ó©w¸q¨ç¦¡¦WºÙ
def <name>(arg1,arg2,.....,argN):
<statements>
Y¦³¦^¶ÇÈ¡A¥i©w¸q¬°
def <name>(arg1,arg2,.....,argN):
<statements>
return <vaule1,value2,.....,valueN)
¦p¡G
>>> def plusAndMulti(x,y):
... intPlus=x+y
... intMulti=x*y
... print 'x+y=%s'%intPlus
... print 'x*y=%s'%intMulti
>>> plusAndMulti(10,20)
x+y=30
x*y=200
>>> def getPlusResult(x,y):
... return x+y
>>> getPlusResult(10,20)
30
>>> def getFirstAndLastElement(lst):
... if not len(lst)>0: return None,None
... return lst[0],lst[len(lst)-1]
>>> lst=[1,2,3,4,5]
>>> getFirstAndLastElement(lst)
(1, 5)
>>> lst=[5]
>>> getFirstAndLastElement(lst)
(5, 5)
>>> lst=[]
>>> getFirstAndLastElement(lst)
(None, None)
>>> lst=[1,2,3,4,5]
>>> b,c=getFirstAndLastElement(lst)
>>> print b,c
1 5
¨ç¦¡¹w³]°Ñ¼ÆÈ
¦b©w¸q¨ç¦¡®É¡A§ÚÌ¥i¥H³]©w°Ñ¼Æªº¹w³]È¡A·í©I¥s¨ç¦¡®É¨S¦³±a¤J¦¹°Ñ¼Æ®É¡A¨t²Î´N·|
¥H¹w³]ªº°Ñ¼ÆȨӴÀ¥N¡C
>>> def getPlusResult(x,y=5):
... return x+y
>>> getPlusResult(4)
9
ª`·N¡G·í°Ñ¼Æ¬O¤@Ó½ÆÂøªº¸ê®Æµ²ºc®É(«D¼Æ¦r©Î¦r¦ê)¡A¸ê®Æ¤º®e¥i¯à·|
¦]¬°²Ö¿n®ÄÀ³¦ÓÁ׶}¤F¹w³]Ȫº³]©w¡C¦p¡G
>>> def appendList(x,y=[]):
... y.append(x)
... return y
>>> appendList(3)
[3]
>>> appendList(4)
[3, 4]
>>> appendList(5)
[3, 4, 5]
¨Ï¥ÎÃöÁä¦r¶ñ¤J°Ñ¼ÆÈ
·í©w¸q¨ç¦¡»Ýn¶Ç¤J¦hӰѼÆȮɡA°£¤F¥i¥H«ö¶¶§Ç¶ñ¤J°Ñ¼ÆÈ¥H¥~¡A¤]
¥i¥H¨Ï¥Î«ü©w°Ñ¼Æ¦WºÙ¨Ó¶ñ¤J°Ñ¼ÆÈ¡A¦p¦¹´N¥i¥H¤£¥²¨Ì·Ó¶¶§Ç¤F¡C
>>> def getGreeting(greeting,name='anonymous',postfix='.'):
... return '%s, %s%s'%(greeting, name, postfix)
>>> getGreeting('Hello',postfix='?')
'Hello, anonymous?'
>>> getGreeting('Hi','Gina','~')
'Hi, Gina~'
>>> getGreeting(postfix='!',name='Tina',greeting='Yo')
'Yo, Tina!'
ª`·N¡G¦b¨ç¼Æ©w¸q®É¡A¾¨¥i¯à±N¨S¦³¹w³]-
Ȫº°Ñ¼Æ±Æ¦b¥ª°¼¡A¥H«K¦b¥¼«ü©w°Ñ¼Æ¦WºÙ®É¡A¨t²Î¯à¹ïÀ³¨ì¥¿½Tªº°Ñ¼Æ¡C
¤£©wӼưѼÆ
·í§A¦b¦Ò¼{¨ç¦¡®É¡AYµLªk½T©w¥i¯à±a¤J°Ñ¼ÆªºÓ¼Æ®É¡A¥i¥H¦b©w¸q¨ç¦¡®É¨Ï¥Î '*' ¥Nªí¤
£©wӼưѼƨөw¸q¨ç¦¡°Ñ¼Æ¡C
>>> def getMultiGreeting(greeting, *name):
... multiName=','.join(name)
... print '%s'%type(name)
... return '%s: %s'%(greeting,multiName)
>>> getMultiGreeting('Hello','eric','Tina','Gina')
<type 'tuple'>
'Hello: eric,Tina,Gina'
>>> getMultiGreeting('Hello','eric','Tina','Gina','Tom','David')
<type 'tuple'>
'Hello: eric,Tina,Gina,Tom,David'
ª`·N¡G¥Ñ '*' ©Ò©w¸qªº°Ñ¼Æ¬O¥Htuple«¬ºA¦s¦b¡A¦]¦¹¥i¥H§â¥¦·ítuple¨Ó¾Þ§@¥¦¡C
Y¨Ï¥Î '**' ¨Ó©w¸q°Ñ¼Æ¡A«h¥i¥H§â¥¦·í¦¨dictªº¸ê®Æ«¬ºA¾Þ§@¥¦¡C¦p¡G
>>> def getUsersNameEmail(name,**options):
... print 'StudentName:%s'%name
... if options.has_key('age'): print 'Age:%s'%options['age']
... if options.has_key('email'): print 'Email:%s'%options['email']
>>> getUsersNameEmail('eric',age=17,email='laaa@hinet.net')
StudentName:eric
Age: 17
Email: laaa@hinet.net
¨ç¦¡¡Gsub() ¨ú¥N
# re.sub()
>>> import re
>>> pwd = re.sub('D','',text) #¤£¬O¼Æ¦rªº¨ú¥N¦¨ªÅ¦r¦ê
>>> print (pwd)
342358359364328963896243642384936234493939
¨ç¦¡¡Gjoin() ¦ê³slist
>>> tmp = re.findall('d', text) # ¬D¥X«D¼Æ¦r¡A²Õ¦¨list
>>> pwd = ''.join(tmp) # ±N¦ê¦C³s±µ°_¨Ó¡A¤¤¶¡¤
£¶ë¥ô¦ó¸ê®Æ
>>> print (pwd)
8784709893727894859089
Python ªºª«¥ó³]p
¦bpython ¤¤°£¤F¥i¥H©w¸q¨ç¦¡¥~¡A¥¦¤]¦P¼Ë¦³ª«¥ó¾É¦Vªº³]-
p¡AclassÃöÁä¦r«h¬O¥Î¨Ó©w¸qª«¥óªºÃþ§O¡Aª«¥óÃþ§O¥i¥H¥Î¨Ó²£¥Íª«¥ó¹êÅé ( instance)
¡A©Ò¥H¥¦¤]¥i¥Hµø¬°¬O¤@ºØ¸ê®Æ«¬ºA¡C
>>> class Student(object):
... number=''
... def __init__(self,number):
... self.number=number
... def set_number(self,number):
... self.number=number
... def get_number(self):
... return self.number
>>> std=Student('')
>>> print std.get_number()
>>> std=Student('N90000001')
>>> print std.get_number()
N90000001
>>> std.set_number('N00010001')
>>> print std.get_number()
N00010001
Studentª«¥óÃþ§O¤U©w¸q¤F " __init__"¡B" set_number"¡B"get_number"¤TӨ禡¡A¨C¤@-
Ө禡ªº²Ä¤@ӰѼƳ£¥²¶·¬Oself¡A¬O¥Î¨Ó¥Nªí©I¥s¦¹¨ç¦¡ªºª«¥ó¹êÅé¡C
number¬O¦¹ª«¥óªºÄÝ©Ê(attribute)¡A
set_number»Pget_number¬O¦¹ª«¥óªº¤èªk(method)¡A
__init__¤èªk¬Oª«¥óªº«Øºc¤l(constructor)¡A¬O¦b«Ø¥ßª«¥ó¹êÅé®É¨t²Î¹w³]©I¥sªº¨ç¦¡¡A
¦b¤Wz¨Ò¤l¤¤«Ø¥ßstd=Student('N90000001')ª«¥óstd®É¡A
´N¬O¹ïÀ³¨ìª«¥óÃþ§O¤Uªº__init__¨ç¦¡¡A'N90000001'«h¬O¹ïÀ³¨ìnumber°Ñ¼Æ-
È¡Aset_number»Pget_numberªº¤èªk¦bª«¥ó²£¥Í®É
´N¥i¥Hª½±µ¨Ï¥Î¡AÃþ¦ü©ójava»y¨¥ªºpublic¤èªk¡A¦p std.set_number('N00010001')
¡Bstd.get_number()¡C
Ãþ§O©w¸q§¹¦¨«á¡A¥i¥H¥Î¨Ó²£¥Í³¦hªºª«¥ó¹êÅé¡A¦Uª«¥ó¹êÅ鶡¨Ã¤£·|¤¬¬Û¼vÅT¡C
>>> s1=Student('N99010001')
>>> s2=Student('N99020002')
>>> s3=Student('N99030003')
>>> print s1.get_number()
N99010001
>>> print s2.get_number()
N99020002
¥t¥~¡A¦b¤Wzªº¨Ò¤l¤¤¡AnumberÄݩʤ]¬OÄÝ©ópublicªºÄÝ©Ê¡Aª«¥ó¥i¥Hª½±µ§ïÅÜnumberªºÈ¡C
>>> s1.number='N99040004'
>>> print s1.get_number()
N99040004
Y¤£·QnÅýÄݩʩΤèªk¥i¥Hª½±µ³Q®³¨Ó¨Ï¥Î¡A§ÚÌ¥i¥H§Q¥Î¨âÓ©³½u "
__"§@¬°«e¸m¦r¦ê¡A¨Ó±N¥¦ÌÁôÂð_¨Ó¡AÃþ¦üjava»y¨¥ªºprotected©Îprivate¥Îªk¡C
>>> class Student(object):
... __number=''
... def __init__(self,number):
... self.__number=number
... self.__initSomething()
... def set_number(self,number):
... self.__number=number
... def get_number(self):
... return self.__number
... def __initSomething(self):
... print 'init something....'
>>> s1=Student('N99010001')
init something....
>>> s1.__name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__name'
>>> s1.__initSomething()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__initSomething'
>>> s1.get_number()
'N99010001'
¦ý¹ï©ó¤F¸Ñpython»y¨¥ªÌ¦Ó¨¥¡A¨ä¹ê³oºØ¤è¦¡¥u¬O±N³o¨Ç¤èªk¤ÎÄÝ©Ê´«Ó¦W¤l¦Ó¤w¡AY¯u-
n©I¥s¥¦Ì¡A¤´µM¬O¥i¥H°µ±o¨ì¡A¥u¬On¦h¤@¹Dµ{§Ç¦Ó¤w¡A§Y¦b¤èªk©ÎÄݩʪº«e±¥[¤W "
_ª«¥óÃþ§O¦WºÙ"
¤~¯àª½±µ¦s¨ú¡C©Ò¥H¡A¥u¦³±oª¾Ãþ§O¦WºÙªº¤~¯àª½±µ¦s¨ú±o¨ì¡A³o¼ËÁÙ¬O¥i¥H°µ¨ì°ò¥»ªº¸ê
°TÁôÂáC
>>> s1._Student__number
'N99010001'
>>> s1._Student__initSomething()
init something....
python ªºª«¥óÄ~©Ó
ª«¥óªºÄ~©ÓÃö«Y( inheritance)¡A¥i²¤ÆÁc½Æ³]-
pªºµ{¦¡½X¡AÅýª«¥ó«O¯d¥Àª«¥óªºÄݩʤΤèªk¡A¨Ã¥i¥H¥[¤W©Î-
קï¦Û¤vªºÄÝ©Ê»P¤èªk¡A³oºØ¤è¦¡¤j¤j´£°ªµ{¦¡³]pªº®Ä²v¡AÄ~©Óªº¤èªk
´N¬O¦bª«¥óÃþ§O¦WºÙ«áªº¤p¬A¸¹¤¤¡A©ñ¤J-
nÄ~©Óªºª«¥óÃþ§O¦WºÙ(¦pStudentª«¥óÃþ§OÄ~©Ó¤Fobjectª«¥ó¡C
>>> class Student(object):
... number=''
... def __init__(self,number):
... self.number=number
... self.__initSomething()
... def set_number(self,number):
... self.number=number
... def get_number(self):
... return self.number
... def __initSomething(self):
... print 'init something....'
>>> class TimeWorker(Student):
... __name=''
... def __init__(self,number,name):
... self.number=number
... self.__name=name
... def set_name(self,name):
... self.__name=name
... def get_name(self):
... return self.__name
>>> tw=TimeWorker('N95050005','eric')
>>> tw.get_number()
'N95050005'
>>> tw.get_name()
'eric'
ª`·N¡GY¬On³QÄ~©Óª«¥ó¤¤ªº¦¨û®É¡A¥i¨Ï¥Îsuper( )¤èªk©I¥s¥ÀÃþ§O¤èªk©ÎÄÝ©Ê¡A¦p-
n©I¥s¥ÀÃþ§Oªº__init__³]©w«Øºc¤l¡A©ñ¤Jªì©lÈ¡C
>>> class Student(object):
... __number=''
... def __init__(self,number):
... self.__number=number
... self.__initSomething()
... def set_number(self,number):
... self.__number=number
... def get_number(self):
... return self.__number
... def __initSomething(self):
... print 'init something....'
>>> class TimeWorker(Student):
... __name=''
... def __init__(self,number,name):
... super(TimeWorker,self).__init__(number)
... self.__name=name
... def set_name(self,name):
... self.__name=name
... def get_name(self):
... return self.__name
>>> tw=TimeWorker('N95050005','eric')
init something....
>>> tw.get_number()
'N95050005'
python ªºÀɮ׳B²z
python n¶}±ÒÀɮ׮ɡA¥i©I¥s¤º«Øªº¨ç¦¡ open(filename, mode)¡Amode¦³¦hºØ¿ï¾Ü¡G
'r' ¡G ¶}±ÒÀɮ׬°Åª¨ú¼Ò¦¡¡A¦¹¬°¹w³]¼Ò¦¡¡C
'w'¡G¶}±ÒÀɮ׬°¥i¼g¤J¼Ò¦¡¡AYÀɮצs¦b¡A«h·|³QÂл¤º®e¡C
'a'¡G¶}±ÒÀɮ׬°¥i¶i¦æ§ÀºÝªþ¥[¼g¤J¼Ò¦¡¡C
'b'¡GÀɮ׶i¦æ¤G¶i¦ì¸ê®Æ³B²z
°Ñ¦Ò¸ê®Æ¡Ghttps://docs.python.org/2/tutorial/inputoutput.html#reading-and-
writing-files
ÀÉ®×¼g¤J¼Ò¦¡
>>> f = open('workfile', 'w')
>>> f.write('This is the entire file.n')
>>> print f
<open file 'workfile', mode 'w' at 0x020C4D88>
>>> f.close()
ÀÉ®×Ū¨ú¼Ò¦¡
>>> myfile=open('workfile')
>>> myfile.readline()
'This is the entire file.n'
>>> myfile.readline()
''
>>> f= open("rw_test", "w") # w¥Nªí¼g¤J¡Aw+«h¬O¨S¦³Àɮתº¸Ü·|¦Û°Ê·s¼W
>>> f.write("Hello 123")
>>> f.close()
>>> f = open ("rw_test", "r") # r¥NªíŪ¨ú
>>> f.read()
'Hello 123'
Àɮתþ¥[¼g¤J¼Ò¦¡
>>> f = open('workfile', 'a')
>>> f.write('Second line of the filen')
>>> f.close()
>>> myfile=open('workfile')
>>> myfile.readline()
'This is the entire file.n'
>>> myfile.readline()
'Second line of the filen'
>>> myfile.readline()
''
>>> data=open('workfile').read()
>>> print data
This is the entire file.
pythonªº¨Ò¥~³B²z
·ípythonªºµ{¦¡½X¦b°õ¦æ®É¡AYµo¥Í»yªk©Îµ{¦¡¹Bºâ¿ù»~®É¡A¨t²Î´N·|¥á¥X¤@-
Ó¨Ò¥~(Exception)¿ù»~¡A¦p¡G
>>> i=0
>>> 10/i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> whild i<10: print i
File "<stdin>", line 1
whild i<10: print i
^
SyntaxError: invalid syntax
¤Wz¨Ò¤l´N¬O·í¸ê®Æ«¬ºA©Î»yªk¿ù»~®É¡Apython ª½Ä¶¾¹´N·|?
¥X(throw)ZeroDivisionError¤ÎSyntaxErrorªº¿ù»~¡A¦pªG¨S¦³¦n¦n³B²z¡Aµ{¦¡´N·|¤
¤Â_¦b¦¹¡AµLªk«ùÄò¶i¦æ¡C
§ÚÌ¥i¥H°w¹ï¯S©wªº¨Ò¥~¿ù»~¨Ó«Ø¥ß±µ¦¬¿ù»~³B²zªºµ{¦¡°Ï¬q
>>> try:
... n=10/0
... print n
... except ZeroDivisionError:
... print 'Davided by 0'
...
Davided by 0
¦¹§Y·í§Ú̹w´Áªº¿ù»~µo¥Í®É¡A´N¥i¥H³z¹L¨Æ«e³]p¦nªº³W«h¨Ó³B²z¬Û¹ïÀ³ªº¿ù»~±¡ªp¡C
¦pªG§A³]pªºµ{¦¡°Ï¶ô¦³¥i¯àµo¥Í³¦h¦UºØ¤£¦Pªº¨Ò¥~±¡ªp¡A§A¥i¥H¨Ï¥Î¦hÓ¤
£¦Pªºexcept¨Ó³B²z©Î¬O¨Ï¥Îelse¨Ó³B²z¨ä¥L¨S¦³³B²z¨ìªº¨Ò¥~ª¬ªp¡C
>>> try:
... readFile=open('testFile.txt','r')
... firstLine=readFile.readline()
... intNum=int(firstLine)
... print intNum
... except IOError:
... print 'Error on opening file or reading first line.'
... except ValueError:
... print 'Cannot convert first line to integer.'
... else:
... print 'Unknow Error'
... finally:
... print 'finally....'
YÀɮפ£¦s¦b¡A«h·|¥X²{
Error on opening file or reading first line.
finally....
YÀɮצs¦b¡A¦ý¤º®eµLªkÂà´«¦¨¾ã¼Æ®É
Cannot convert first line to integer.
finally....
¦pªG¨S¦³µo¥Í¨Ò¥~¡A°£¤F·|°õ¦æ¥Xµ²ªG¥~¡Aelseªº¤º®e¤]·|°õ¦æ
...
45
Unknow Error
finally....
finally?zªº¤º®e«h¬O¤£ºÞ°õ¦æµ²ªG¥¿±`©Î¬Oµo¥Í¨Ò¥~®É¡A¥¦³£·|Â÷¶}try¤§«e°õ¦æ¡C
¥t¥~¡A§Ṳ́]¥i¥H±N¿ù»~°T®§Åª¨ú¥X¨Ó¡A¦p¡G
>>> try:
... readFile=open('testFile1.txt','r')
... firstLine=readFile.readline()
... intNum=int(firstLine)
... print intNum
... except Exception as ex:
... print 'Error message is %s'%ex
... else:
... print 'Unknow Error'
... finally:
... print 'finally....'
...
Error message is [Errno 2] No such file or directory: 'testFile1.txt'
finally....
python ¦Ûq¨Ò¥~³B²z
¦bµ{¦¡½X¤¤¡AY¯à¹w´ú·|µo¥Íªº¨Ò¥~±¡§Î¡A§A´N¥i¥H¨Ï¥ÎraiseÃöÁä¦r¨Ó¤â°Ê?¥X¤@-
Ó¨Ò¥~ª«¥ó¡C
>>> def getDivisionResult(intNum1,intNum2):
... if not intNum2:
... raise ZeroDivisionError('Number 2 can not be zero')
... else:
... return intNum1/intNum2
>>> try:
... getDivisionResult(10,0)
... except ZeroDivisionError as err:
... print 'Error Message is %s'%err
...
Error Message is Number 2 can not be zero
>>>
>>> try:
... getDivisionResult(10,5)
... except ZeroDivisionError as err:
... print 'Error Message is %s'%err
...
2
>>>
¦UºØ«¬¦¡ªºerror ª«¥ó¡A¥i°Ñ¦Ò¡Ghttps://docs.python.org/2/library/exceptions.html
¥t¥~¡A§Ṳ́]¥i¥H¦Û¦æ©w¸q¨Ò¥~ª«¥ó¡A¦Û¦æ©w¸qªºª«¥ó¡A¥²¶·nÄ~©Ó¦ÛExceptionª«¥óÃþ§O¡C
>>> class DivisionErr(Exception):
... def __init__(self,msg):
... self.message=msg
>>> def getDivisionResult(intNum1,intNum2):
... if not intNum2:
... raise DivisionErr('Number 2 can not be zero')
... else:
... return intNum1/intNum2
>>> try:
... getDivisionResult(10,0)
... except DivisionErr as err:
... print err.message
...
Number 2 can not be zero
Y§A·Q-
nÅý§A©w¸qªºª«¥ó¹êÅé¹³¤@¯ë±`¨£¨ìªº¨Ò¥~ª«¥ó¤@¼Ë¡A¯à°÷ª½±µ³z¹Lª«¥ó¹êÅé¨Ó¿é¥X®É¡A§A¥
²¶·¦bª«¥ó¤¤¥[¤J __str__ ªºª«¥ó¤èªk¡C
>>> class DivisionErr(Exception):
... def __init__(self,msg):
... self.message=msg
... def __str__(self):
... return self.message
>>> def getDivisionResult(intNum1,intNum2):
... if not intNum2:
... raise DivisionErr('Number 2 can not be zero')
... else:
... return intNum1/intNum2
>>> try:
... getDivisionResult(10,0)
... except DivisionErr as err:
... print 'Error message is %s'%err
...
Error message is Number 2 can not be zero
python ªº¼Ò²Õ³]p
¦bÀ³¥Îµ{¦¡¶}µoªº¹Lµ{¤¤¡A§ÚÌ·|±N¬ÛÃöªº¨ç¦¡©ÎÃþ§Oµ{¦¡½X²Õ¦X¦b¦P¤@¤äµ{¦¡¡A³oÓ§Ú-
̺٤§¬°¼Ò²Õ¡A·í³oÓ¼Ò²Õ»Ýn³Q¨ä¥¦µ{¦¡¤Þ¥Î®É¡A¥i¥H¨Ï¥Îimport
ªº«ü¥O¨Ó±N¼Ò²Õ¤Þ¤J¡A¸g±`¤@ÓÀ³¥Îµ{¦¡¬O¥²¶·n¤Þ¥Î¦h-
Ó¼Ò²Õmodule¤~¯à§¹¦¨À³°õ¦æªº¥ô°È¡C
¹ï¨C¤@ÓpythonÀɮצӨ¥¡A§Ṳ́]¥i¥H±N¥¦µø¬°¤@Ó¼Ò²Õ¡A¨Ò¦p¡A§Ú̦bmyMathFun.pyÀɮפ
¤³]p¤@Ó¥i¥Hpºâ¶¥¼h¥[Á`ªº¨ç¦¡¡G
>>> # myMathFun.py
>>> def sumHierarchy(n):
... if n<2: return 1
... else: return n+sumHierarchy(n-1)
¦pªGn¦b¨ä¥¦ªºµ{¦¡¤¤°õ¦æ¡A´N¥²¶·§Q¥Îimport ªº»yªk©Îfrom xxx import
xxxªº»yªk±N¼Ò²Õ©Î¼Ò²Õ¤¤ªº¨ç¦¡¤Þ¤J¡G
>>> # main.py
>>> import myMathFun
>>> def main():
... print '1+2+...5= %d'%myMathFun.sumHierarchy(5)
>>> if __name__=='__main__':
... main()
·ín¤Þ¤J¯S©wª«¥óÃþ§O©Î¨ç¦¡®É¡G
>>> # main.py
>>> from myMathFun import sumHierarchy
>>> def main():
... print '1+2+...5= %d'%sumHierarchy(5)
>>> if __name__=='__main__':
... main()
°õ¦æµ²ªG¬°¡G
python main.py
1+2+...5= 15
¦b¤Wz¨Ò¤l¤¤ __name__ ±`¼Æ¬O¨C¤@Ó¼Ò²Õ³£¦³ªº¤º«Ø±`¼Æ¡A³oÓ±`¼ÆªºÈ
´N¬O¼Ò²Õªº¦WºÙ(¤]¬OÀɮתº¦WºÙ)¡A·ípythonª½Ä¶¾¹¦b°õ¦æ¤@ÓpythonÀɮ׮ɡA¥¦·|
±N¦¹±`¼Æ__name__ªºÈ§ï¦¨__main__¤]´N¬O¤Á¤Jµ{¦¡°õ¦æªºÂI¡A©Ò¥H¦b¦¹ if §PÂ_¦¡¤
¤©Ò°õ¦æªº¨ç¦¡©Îµ{¦¡´N·|¦bµ{¦¡¤@¶}©l°õ¦æ®É³Q¸ü¤J¹B§@¡C
python ®M¥ó³B²z
¦bpython¤¤¡A§A¥i¥H±N¦hÓ¦PÃþ«¬©ÎÄݩʪº¼Ò²Õ¶°¤¤¦b¦P¤@ӥؿý¤¤¡A¨Ã¦b¥Ø¿ý¤¤¥[¤J
__init__.pyªºÀɮסA¨Ó²Õ¦X¦¨¤@Ó®M¥ó¡C
°²³]¦³Ó®M¥óªº¥Ø¿ý¦¨ûµ²ºc¦p¤U¡G
mylib/
__init__.py
myMathFun.py
countNum.py
Yn¤Þ¤JmyMathFun¼Ò²Õ¡A¥i¥H¦bÀɮפW¤è¥[¤J
>>> from mylib import myMathFun
Yn¨Ï¥ÎmyMathFun¤¤ªºÃþ§Oª«¥ó©Î¨ç¦¡¡A¥i¥Î
>>> #main.py
>>> from mylib import myMathFun
.....
.....
>>> myMathFun.sumHierarchy(5)
¦b __init__.py¤¤©Ò©w¸qªºª«¥óÃþ§O©Î¨ç¦¡¡A¥iª½±µ¤Þ¤J¨Ï¥Î¡C
>>> #mylib/__init__,py
>>> def sayHello():
... print ("hello')
>>> #main.py
>>> from mylib import sayHello
.....
.....
>>> sayHello()
¸ü¤J¼Ò²Õ
½d¨Ò1¡G¸ü¤J¼Ò²Õ
>>> import random # ¸ü¤Jrandom¼Ò²Õ
>>> print(random.randint(2,29)) # ¨Ï¥Î¨ä¤¤ªºrandint¨ç¦¡
>>> from random import randinr # ¸ü¤Jrandomªºrandint¼Ò²Õ
>>> print(randint(2,29)) # ¨Ï¥Î®É¤£¥Î¼g¤@¤j¦ê
½d¨Ò2¡GŪ²Õºô¶
>>> from urllib.request import urlopen # ¸ü¤JŪ¨úºô¶¼Ò²Õ
>>> data = urlopen("http://www.cs.pu.edu.tw/~ylyang/vcs_git.html").read()
>>> str = data.decode() # Âনutf-8®æ¦¡
>>> print (str)
python ¤pµ{¦¡»s§@½d¨Ò
¸Õ§Q¥Î¼Ò²Õ³]p¤@Ó¥i¥H¿ï¾Ü¤GºØ¹Bºâªºpythonµ{¦¡
(1)¥i¥H¿é¤J¤GÓ¾ã¼Æ¥|«h¹Bºâªº¹Bºâ¾¹
(2)¥i¥H¿é¤J¤@Ó¾ã¼ÆÈ,¨Ãpºâ¥¦ªº¶¥¼h¼¿n
(3)Â÷¶}
¸Ñµª:
# homework.py
# coding: utf-8
import re,math
def isValidFormula(strFormula):
regexp =re.compile(r'd{1,5}[+|-|*|/]d{1,5}')
if regexp.search(strFormula): return True
return False
def getArithmeticResult(strFormula):
try:
if isValidFormula(strFormula): return eval(strFormula)
else: return 'input error'
except: return 'input error'
def getFactorialResult(strNum):
if strNum.isdigit(): return math.factorial(int(strNum))
else: return 'input error'
def main():
while True:
print u'''
½Ð¿ï¾Ü
(1)¥i¥H¿é¤J¤GÓ¾ã¼Æ¥|«h¹Bºâªº¹Bºâ¾¹
(2)¥i¥H¿é¤J¤@Ó¾ã¼ÆÈ,¨Ãpºâ¥¦ªº¶¥¼h¼¿n
(3)Â÷¶}
'''
strChoice=raw_input('Select:')
if strChoice.strip()=='1':
print u'½Ð¿é¤J¹Bºâ¦¡:'
strFormula=raw_input()
print u'%s=%s'%(strFormula,getArithmeticResult(strFormula))
elif strChoice.strip()=='2':
print u'½Ð¿é¤J¶¥¼h¼Æ¦r:'
strNum=raw_input()
print u'%s!=%s'%(strNum,getFactorialResult(strNum))
elif strChoice.strip()=='3': break
else: print 'your choice is error'
print '=========================================='
if __name__=='__main__':
main()

More Related Content

What's hot

Cetemin explotacion minas practica de topografia general
Cetemin explotacion minas practica de topografia generalCetemin explotacion minas practica de topografia general
Cetemin explotacion minas practica de topografia generalJuan Carlos Mamani
 
سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)
سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)
سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)Ahmed@3604
 
1 b1499reqts
1 b1499reqts1 b1499reqts
1 b1499reqtsDanu Dani
 
Ohp Seijoen H20 06 Mojiretsu
Ohp Seijoen H20 06 MojiretsuOhp Seijoen H20 06 Mojiretsu
Ohp Seijoen H20 06 Mojiretsusesejun
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesAbdul Rahman Sherzad
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
To who is who της Ελληνικής Προεδρίας
To who is who της Ελληνικής Προεδρίας To who is who της Ελληνικής Προεδρίας
To who is who της Ελληνικής Προεδρίας Vassilios Fevgas
 
Seerat unnabi - Mufti Zia ud Din - Abul Hasanat Research Academy
Seerat unnabi - Mufti Zia ud Din - Abul Hasanat Research AcademySeerat unnabi - Mufti Zia ud Din - Abul Hasanat Research Academy
Seerat unnabi - Mufti Zia ud Din - Abul Hasanat Research AcademyMuhammad Nabeel Musharraf
 
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
   מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה    מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה Igor Kleiner
 
Ahmadiyya national-assembly-pakistan-1974
Ahmadiyya national-assembly-pakistan-1974Ahmadiyya national-assembly-pakistan-1974
Ahmadiyya national-assembly-pakistan-1974muzaffertahir9
 
Zdjhgjkh
ZdjhgjkhZdjhgjkh
Zdjhgjkhsandra
 
1024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 20131024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 2013Martin Kleppe
 
Karamat e sahaba.urdu
Karamat e sahaba.urduKaramat e sahaba.urdu
Karamat e sahaba.urdudawateislami
 

What's hot (20)

Cetemin explotacion minas practica de topografia general
Cetemin explotacion minas practica de topografia generalCetemin explotacion minas practica de topografia general
Cetemin explotacion minas practica de topografia general
 
Expressions and Variables
Expressions and VariablesExpressions and Variables
Expressions and Variables
 
سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)
سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)
سیرت مصطفٰی صلّی اللہ تعالٰی علیہ وسلّم_Seerat e Mustafa (saw)
 
1 b1499reqts
1 b1499reqts1 b1499reqts
1 b1499reqts
 
Denuncia roubo
Denuncia   rouboDenuncia   roubo
Denuncia roubo
 
كتاب ظلال العرش برواية ورش
كتاب ظلال العرش برواية ورشكتاب ظلال العرش برواية ورش
كتاب ظلال العرش برواية ورش
 
Ohp Seijoen H20 06 Mojiretsu
Ohp Seijoen H20 06 MojiretsuOhp Seijoen H20 06 Mojiretsu
Ohp Seijoen H20 06 Mojiretsu
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
To who is who της Ελληνικής Προεδρίας
To who is who της Ελληνικής Προεδρίας To who is who της Ελληνικής Προεδρίας
To who is who της Ελληνικής Προεδρίας
 
Golf game vba code
Golf game vba codeGolf game vba code
Golf game vba code
 
Seerat unnabi - Mufti Zia ud Din - Abul Hasanat Research Academy
Seerat unnabi - Mufti Zia ud Din - Abul Hasanat Research AcademySeerat unnabi - Mufti Zia ud Din - Abul Hasanat Research Academy
Seerat unnabi - Mufti Zia ud Din - Abul Hasanat Research Academy
 
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
   מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה    מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
 
Ahmadiyya national-assembly-pakistan-1974
Ahmadiyya national-assembly-pakistan-1974Ahmadiyya national-assembly-pakistan-1974
Ahmadiyya national-assembly-pakistan-1974
 
Zdjhgjkh
ZdjhgjkhZdjhgjkh
Zdjhgjkh
 
Memoria descriptiva
Memoria descriptivaMemoria descriptiva
Memoria descriptiva
 
Matemática - Tercer Ciclo - Actividades - Nivel Primario
Matemática - Tercer Ciclo - Actividades - Nivel PrimarioMatemática - Tercer Ciclo - Actividades - Nivel Primario
Matemática - Tercer Ciclo - Actividades - Nivel Primario
 
Theme
ThemeTheme
Theme
 
1024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 20131024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 2013
 
Karamat e sahaba.urdu
Karamat e sahaba.urduKaramat e sahaba.urdu
Karamat e sahaba.urdu
 

Viewers also liked

Energía eólica y solar
Energía eólica y solarEnergía eólica y solar
Energía eólica y solarSandy Anaya
 
Edició de textos
Edició de textosEdició de textos
Edició de textosMar_127
 
Media pics
Media pics Media pics
Media pics kyeallen
 
CONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBE
CONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBECONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBE
CONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBEJavier Trespalacios
 
$100 challenge final presentation
$100 challenge final presentation$100 challenge final presentation
$100 challenge final presentationMelanie Erickson
 
Drew danzeisen resume 2016
Drew danzeisen resume 2016Drew danzeisen resume 2016
Drew danzeisen resume 2016Drew Danzeisen
 
FD Confidential OnLine Brochure
FD Confidential OnLine BrochureFD Confidential OnLine Brochure
FD Confidential OnLine BrochureJo Moir
 
Masked madness film
Masked madness filmMasked madness film
Masked madness filmSQUIRREL47
 
Women's Access to Healthcare - Midwives of Georgia Presentation
Women's Access to Healthcare - Midwives of Georgia PresentationWomen's Access to Healthcare - Midwives of Georgia Presentation
Women's Access to Healthcare - Midwives of Georgia PresentationGeorgia Commission on Women
 
Ecosystems Angel naturales tema 5
Ecosystems Angel naturales tema 5Ecosystems Angel naturales tema 5
Ecosystems Angel naturales tema 5angelayusodefensa9
 

Viewers also liked (18)

Energía eólica y solar
Energía eólica y solarEnergía eólica y solar
Energía eólica y solar
 
Entrevista (1)
Entrevista (1)Entrevista (1)
Entrevista (1)
 
Process Design
Process DesignProcess Design
Process Design
 
Dreams
DreamsDreams
Dreams
 
Edició de textos
Edició de textosEdició de textos
Edició de textos
 
Media pics
Media pics Media pics
Media pics
 
Prezi marc
Prezi marcPrezi marc
Prezi marc
 
CONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBE
CONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBECONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBE
CONCEPT et PLANIFICATION ENERGETIQUE TERRITORIALE - ORBE
 
$100 challenge final presentation
$100 challenge final presentation$100 challenge final presentation
$100 challenge final presentation
 
Drew danzeisen resume 2016
Drew danzeisen resume 2016Drew danzeisen resume 2016
Drew danzeisen resume 2016
 
FD Confidential OnLine Brochure
FD Confidential OnLine BrochureFD Confidential OnLine Brochure
FD Confidential OnLine Brochure
 
swk 350 term paper
swk 350 term paperswk 350 term paper
swk 350 term paper
 
Masked madness film
Masked madness filmMasked madness film
Masked madness film
 
Who am i presentation
Who am i presentationWho am i presentation
Who am i presentation
 
Proyectos
ProyectosProyectos
Proyectos
 
Full script
Full script Full script
Full script
 
Women's Access to Healthcare - Midwives of Georgia Presentation
Women's Access to Healthcare - Midwives of Georgia PresentationWomen's Access to Healthcare - Midwives of Georgia Presentation
Women's Access to Healthcare - Midwives of Georgia Presentation
 
Ecosystems Angel naturales tema 5
Ecosystems Angel naturales tema 5Ecosystems Angel naturales tema 5
Ecosystems Angel naturales tema 5
 

Similar to Python 入門初體驗(程式語法)

آسان اصول حدیث۔سیف اللہ رحمانی.pdf
آسان اصول حدیث۔سیف اللہ رحمانی.pdfآسان اصول حدیث۔سیف اللہ رحمانی.pdf
آسان اصول حدیث۔سیف اللہ رحمانی.pdfFaizan ali Siddiqui
 
資料庫期末Project Proposal
資料庫期末Project Proposal資料庫期末Project Proposal
資料庫期末Project ProposalFrank Chang
 
SK컴즈 행복화실 9주 과정 전체
SK컴즈 행복화실 9주 과정 전체SK컴즈 행복화실 9주 과정 전체
SK컴즈 행복화실 9주 과정 전체Jinho Jung
 
నీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-III
నీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-IIIనీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-III
నీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-IIIVenkat Gandhi Poddutoori
 
博弈天使 Erwin Huang Interview
博弈天使 Erwin Huang Interview博弈天使 Erwin Huang Interview
博弈天使 Erwin Huang InterviewErwin Huang
 
とちぎRuby会議01(原)
とちぎRuby会議01(原)とちぎRuby会議01(原)
とちぎRuby会議01(原)Shin-ichiro HARA
 
WxHaskell
WxHaskellWxHaskell
WxHaskellina job
 
IIT-JEE Mains 2016 Online Previous Question Paper Day 2
IIT-JEE Mains 2016 Online Previous Question Paper Day 2IIT-JEE Mains 2016 Online Previous Question Paper Day 2
IIT-JEE Mains 2016 Online Previous Question Paper Day 2Eneutron
 
Noip 2016-day2
Noip 2016-day2Noip 2016-day2
Noip 2016-day2德源 何
 
ใบความรู้ที่ 2.5 body section
ใบความรู้ที่ 2.5 body sectionใบความรู้ที่ 2.5 body section
ใบความรู้ที่ 2.5 body sectionSamorn Tara
 
Engleza incepatori
Engleza incepatoriEngleza incepatori
Engleza incepatoriadeadina
 
Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonMoses Boudourides
 
Engleza pentru incepatori
Engleza pentru incepatori Engleza pentru incepatori
Engleza pentru incepatori innarotarciuc
 

Similar to Python 入門初體驗(程式語法) (20)

Mgd10 lab03
Mgd10 lab03Mgd10 lab03
Mgd10 lab03
 
آسان اصول حدیث۔سیف اللہ رحمانی.pdf
آسان اصول حدیث۔سیف اللہ رحمانی.pdfآسان اصول حدیث۔سیف اللہ رحمانی.pdf
آسان اصول حدیث۔سیف اللہ رحمانی.pdf
 
資料庫期末Project Proposal
資料庫期末Project Proposal資料庫期末Project Proposal
資料庫期末Project Proposal
 
raseswara.compressed
raseswara.compressedraseswara.compressed
raseswara.compressed
 
SK컴즈 행복화실 9주 과정 전체
SK컴즈 행복화실 9주 과정 전체SK컴즈 행복화실 9주 과정 전체
SK컴즈 행복화실 9주 과정 전체
 
నీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-III
నీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-IIIనీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-III
నీళ్ళు నిజాలు 3 Er. Late R. Vidyasagar Rao NEELLU - NIJAALU-III
 
Coverletter&Resume41416
Coverletter&Resume41416Coverletter&Resume41416
Coverletter&Resume41416
 
Ecuacionesfuncionales2 1
Ecuacionesfuncionales2 1Ecuacionesfuncionales2 1
Ecuacionesfuncionales2 1
 
博弈天使 Erwin Huang Interview
博弈天使 Erwin Huang Interview博弈天使 Erwin Huang Interview
博弈天使 Erwin Huang Interview
 
とちぎRuby会議01(原)
とちぎRuby会議01(原)とちぎRuby会議01(原)
とちぎRuby会議01(原)
 
Prueba saber ingles-
Prueba saber ingles-Prueba saber ingles-
Prueba saber ingles-
 
WxHaskell
WxHaskellWxHaskell
WxHaskell
 
Gsp53 1
Gsp53 1Gsp53 1
Gsp53 1
 
IIT-JEE Mains 2016 Online Previous Question Paper Day 2
IIT-JEE Mains 2016 Online Previous Question Paper Day 2IIT-JEE Mains 2016 Online Previous Question Paper Day 2
IIT-JEE Mains 2016 Online Previous Question Paper Day 2
 
Noip 2016-day2
Noip 2016-day2Noip 2016-day2
Noip 2016-day2
 
ใบความรู้ที่ 2.5 body section
ใบความรู้ที่ 2.5 body sectionใบความรู้ที่ 2.5 body section
ใบความรู้ที่ 2.5 body section
 
Ecuacionesfuncionales1 1
Ecuacionesfuncionales1 1Ecuacionesfuncionales1 1
Ecuacionesfuncionales1 1
 
Engleza incepatori
Engleza incepatoriEngleza incepatori
Engleza incepatori
 
Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την Python
 
Engleza pentru incepatori
Engleza pentru incepatori Engleza pentru incepatori
Engleza pentru incepatori
 

More from 政斌 楊

iOS swift 玩 soket 聊天通訊程式
iOS swift 玩 soket 聊天通訊程式iOS swift 玩 soket 聊天通訊程式
iOS swift 玩 soket 聊天通訊程式政斌 楊
 
iOS Swift & OCR 玩文字辨識
iOS Swift & OCR 玩文字辨識iOS Swift & OCR 玩文字辨識
iOS Swift & OCR 玩文字辨識政斌 楊
 
深入學習 iBeacon 之 iOS swift 程式設計
深入學習 iBeacon 之 iOS swift 程式設計深入學習 iBeacon 之 iOS swift 程式設計
深入學習 iBeacon 之 iOS swift 程式設計政斌 楊
 
Android Studio & Cloud Vision API 玩圖像辨識
Android Studio & Cloud Vision API 玩圖像辨識Android Studio & Cloud Vision API 玩圖像辨識
Android Studio & Cloud Vision API 玩圖像辨識政斌 楊
 
iOS swift & Cloud Vision API 玩圖像辨識
iOS swift & Cloud Vision API 玩圖像辨識iOS swift & Cloud Vision API 玩圖像辨識
iOS swift & Cloud Vision API 玩圖像辨識政斌 楊
 
Android studio 之 i beacon 藍芽應用開發學習
Android studio 之 i beacon 藍芽應用開發學習Android studio 之 i beacon 藍芽應用開發學習
Android studio 之 i beacon 藍芽應用開發學習政斌 楊
 
Python vs json 玩open data
Python vs json 玩open dataPython vs json 玩open data
Python vs json 玩open data政斌 楊
 
iOS swift 之 iBeacon 藍芽應用開發學習
iOS swift 之 iBeacon 藍芽應用開發學習iOS swift 之 iBeacon 藍芽應用開發學習
iOS swift 之 iBeacon 藍芽應用開發學習政斌 楊
 
Corona 初探 lua 語言,玩跨平台(iOS & android) 行動裝置開發工具
Corona 初探 lua 語言,玩跨平台(iOS &  android) 行動裝置開發工具Corona 初探 lua 語言,玩跨平台(iOS &  android) 行動裝置開發工具
Corona 初探 lua 語言,玩跨平台(iOS & android) 行動裝置開發工具政斌 楊
 
Golang 入門初體驗
Golang 入門初體驗Golang 入門初體驗
Golang 入門初體驗政斌 楊
 
Android studio 2.2 初體驗 &amp; 玩 face book sdk
Android studio 2.2 初體驗 &amp; 玩 face book sdkAndroid studio 2.2 初體驗 &amp; 玩 face book sdk
Android studio 2.2 初體驗 &amp; 玩 face book sdk政斌 楊
 
Python 入門初體驗
Python 入門初體驗Python 入門初體驗
Python 入門初體驗政斌 楊
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdkI os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdk政斌 楊
 
Android studio 之 fcm 推播服務
Android studio 之 fcm 推播服務Android studio 之 fcm 推播服務
Android studio 之 fcm 推播服務政斌 楊
 
I os swift 之 fcm 推播服務
I os swift 之 fcm 推播服務I os swift 之 fcm 推播服務
I os swift 之 fcm 推播服務政斌 楊
 
Android &amp; fire base 玩上雲端囉
Android &amp; fire base 玩上雲端囉Android &amp; fire base 玩上雲端囉
Android &amp; fire base 玩上雲端囉政斌 楊
 
iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉政斌 楊
 
Android studio 接力使力之玩 open data
Android studio 接力使力之玩 open dataAndroid studio 接力使力之玩 open data
Android studio 接力使力之玩 open data政斌 楊
 
iOS swift 接力使力之玩 open data
iOS swift 接力使力之玩 open dataiOS swift 接力使力之玩 open data
iOS swift 接力使力之玩 open data政斌 楊
 
Android app 入門第一步
Android app 入門第一步Android app 入門第一步
Android app 入門第一步政斌 楊
 

More from 政斌 楊 (20)

iOS swift 玩 soket 聊天通訊程式
iOS swift 玩 soket 聊天通訊程式iOS swift 玩 soket 聊天通訊程式
iOS swift 玩 soket 聊天通訊程式
 
iOS Swift & OCR 玩文字辨識
iOS Swift & OCR 玩文字辨識iOS Swift & OCR 玩文字辨識
iOS Swift & OCR 玩文字辨識
 
深入學習 iBeacon 之 iOS swift 程式設計
深入學習 iBeacon 之 iOS swift 程式設計深入學習 iBeacon 之 iOS swift 程式設計
深入學習 iBeacon 之 iOS swift 程式設計
 
Android Studio & Cloud Vision API 玩圖像辨識
Android Studio & Cloud Vision API 玩圖像辨識Android Studio & Cloud Vision API 玩圖像辨識
Android Studio & Cloud Vision API 玩圖像辨識
 
iOS swift & Cloud Vision API 玩圖像辨識
iOS swift & Cloud Vision API 玩圖像辨識iOS swift & Cloud Vision API 玩圖像辨識
iOS swift & Cloud Vision API 玩圖像辨識
 
Android studio 之 i beacon 藍芽應用開發學習
Android studio 之 i beacon 藍芽應用開發學習Android studio 之 i beacon 藍芽應用開發學習
Android studio 之 i beacon 藍芽應用開發學習
 
Python vs json 玩open data
Python vs json 玩open dataPython vs json 玩open data
Python vs json 玩open data
 
iOS swift 之 iBeacon 藍芽應用開發學習
iOS swift 之 iBeacon 藍芽應用開發學習iOS swift 之 iBeacon 藍芽應用開發學習
iOS swift 之 iBeacon 藍芽應用開發學習
 
Corona 初探 lua 語言,玩跨平台(iOS & android) 行動裝置開發工具
Corona 初探 lua 語言,玩跨平台(iOS &  android) 行動裝置開發工具Corona 初探 lua 語言,玩跨平台(iOS &  android) 行動裝置開發工具
Corona 初探 lua 語言,玩跨平台(iOS & android) 行動裝置開發工具
 
Golang 入門初體驗
Golang 入門初體驗Golang 入門初體驗
Golang 入門初體驗
 
Android studio 2.2 初體驗 &amp; 玩 face book sdk
Android studio 2.2 初體驗 &amp; 玩 face book sdkAndroid studio 2.2 初體驗 &amp; 玩 face book sdk
Android studio 2.2 初體驗 &amp; 玩 face book sdk
 
Python 入門初體驗
Python 入門初體驗Python 入門初體驗
Python 入門初體驗
 
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdkI os swift 3.0 初體驗 &amp; 玩 facebook sdk
I os swift 3.0 初體驗 &amp; 玩 facebook sdk
 
Android studio 之 fcm 推播服務
Android studio 之 fcm 推播服務Android studio 之 fcm 推播服務
Android studio 之 fcm 推播服務
 
I os swift 之 fcm 推播服務
I os swift 之 fcm 推播服務I os swift 之 fcm 推播服務
I os swift 之 fcm 推播服務
 
Android &amp; fire base 玩上雲端囉
Android &amp; fire base 玩上雲端囉Android &amp; fire base 玩上雲端囉
Android &amp; fire base 玩上雲端囉
 
iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉iOS Swift & FireBase 玩上雲端囉
iOS Swift & FireBase 玩上雲端囉
 
Android studio 接力使力之玩 open data
Android studio 接力使力之玩 open dataAndroid studio 接力使力之玩 open data
Android studio 接力使力之玩 open data
 
iOS swift 接力使力之玩 open data
iOS swift 接力使力之玩 open dataiOS swift 接力使力之玩 open data
iOS swift 接力使力之玩 open data
 
Android app 入門第一步
Android app 入門第一步Android app 入門第一步
Android app 入門第一步
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Python 入門初體驗(程式語法)

  • 1. ³æ¦æµù¸Ñ >>> #print ('§Ú³Qµù¸Ñ¤F~') >>> print ('§Ú¨S³Qµù¸Ñ¡I') >>> # print ('§Ú¤S³Qµù¸Ñ¤F!!') >>> print ('«¢«¢«¢«¢') §Ú¨S³Qµù¸Ñ¡I «¢«¢«¢«¢ ¦h¦æµù¸Ñ¡G¥Î ''' ¥]¦í·Qnµù¸Ñªº¤º®e >>> n = 9 >>> m = 10 >>> ''' print( '±q³o¦æ¶}©l" ) >>> n = 0 >>> m = 1 >>> print( '¤@ª½µù¸Ñ¨ì³oÃä' ) ''' >>> print ( n, m ) 9 10 python ¤¤¥i¥Hª½±µ§Q¥Î²Å¸¹¨ÓÀx¦s¼ÆÈ¡A¦r¦ê©Î¸ê®Æµ²ºc¡A¤]´N¬O§Ú- ̩ҿתºÅܼơA·íÅܼƦs©ñ¸ê®Æ«á¡A´N¥i¥Hª½±µ®³¨Ó¹Bºâ©Î§@¨ä¥¦³B²z¡A¤£¥²¶i¦æ«Å§i¡C >>> x=6 >>> print x 6 >>> print x+2 8 >>> y='abc' >>> print y+'def' abcdef >>> y=y+'def' >>> print y abcdef >>> z=2.3 >>> print z+x 8.3 python ªº¼Æȸê®Æ«¬ºA¦³¤TºØ¡G¾ã¼Æ(integer)¡B¯BÂI¼Æ(float)¤Î½Æ¼Æ(complex number)¡C ¾ã¼Æ¤Î¯BÂI¼Æ¥i¥Hª½±µ¶i¦æ¥|«h¹Bºâ¡B¾l¼Æ¹Bºâ¤Î«ü¼Æ¹Bºâ¡A¨t²Î·|¦Û°ÊÂà ´«¬°½d³ò¤jªº«¬ºA¡C >>> 10+2 12 >>> 4.5+6 10.5 >>> 2**3 8 >>> 2^5 7 >>> 2.5/5 0.5 >>> 16**0.25 2.0
  • 2. °£ªk¹Bºâ«h¨Ì·Ó±z©Ònªºµ²ªG¨Ó°Ï¤À¬°¾ã¼Æ°£ªk»P¯BÂI¼Æ°£ªk¡C Y°£¼Æ»P³Q°£¼Æ¬Ò¬°¾ã¼Æ®É¡A©Ò±o¨ìªºµ²ªG¥u¦³°Óªº¾ã¼Æ³¡¥÷¡C Y°£¼Æ©Î³Q°£¼Æ¨ä¤¤¤@Ó¬°¯BÂI¼Æ®É¡A©Ò±o¨ìªºµ²ªG´N·|¬O±a¦³¤p¼Æ§¹¾ãªº°Ó¡C >>> 3/2 1 >>> 3.0/2 1.5 >>> 3/2.0 1.5 >>> 10.0/3 3.3333333333333335 ¹ï©ó¯BÂI¼Æ¦Ó¨¥¡A¦]¼Æȧe²{¦ì¼Æ¦³¡Aªí¥Üªk·|±N³¡¥÷¦ì¼Æ±Ë¥h¡A³y¦¨Åã¥Ü¤W·| ¦³»~®t¡A·U¤j¶q¹Bºâ»~®t·|·U¤j¡A¦ý¹ï©ó¹ê»Úµ²ªGÅã¥Ü¤W¥i¥H§Q¥ÎÂà ´«¬°¾ã¼Æint()©Î¨ú¯BÂI¼Æ¦³®Ä¦ì¼Æround()¨Ó¸Ñ¨M³oÓ°ÝÃD¡A¦p¡G >>> x=0.1 >>> print x 0.1 >>> x**10 1.0000000000000006e-10 >>> x**50 1.0000000000000027e-50 ¾ã¼Æ»P¯BÂI¼ÆªºÂà´«¥i¥H§Q¥Îint( )»Pfloat( )¨âÓ¨ç¼Æ¨Ó§¹¦¨¡C >>> x=4.9 >>> int(x) 4 >>> y=5 >>> float(y) 5.0 >>> z=float(y)/x >>> z 1.0204081632653061 >>> round(z,5) 1.02041 ¹ï©ó½Æ¼Æªº¸ê®Æ«¬ºA¡A¥i¥H¨Ï¥Î x+yj ©Î x+yJ ¨âºØ(j©ÎJ)¨Óªí¥Ü¡A¨ä¤ ¤xªí¥Ü¹ê³¡¡Ayªí¥Üµê³¡¡C >>> x=1+4j >>> print x (1+4j) >>> y=2+3j >>> y (2+3j) >>> x+y (3+7j) >>> x*y (-10+11j)
  • 3. >>> x+6 (7+4j) >>> x**2 (-15+8j) >>> y**2 (-5+12j) Yn³æ¿W¨ú¥X½Æ¼Æªº¹ê³¡©Îµê³¡¡A¥i¥H¨Ï¥Îreal¤Îimag¨âÓÄÝ©Ê¡C >>> x.real 1.0 >>> x.imag 4.0 python¤¤¦r¦ê¸ê®Æ¥i¥H¥Î¥b«¬ªº³æ¤Þ¸¹ ( ' )©ÎÂù¤Þ¸¹( " )¨Ó±N¦r¦ê¤º®e¥]ÂЦb¨ä¤¤ ¡A¦pªG¦b¨ä¤¤¦³¥²nÅã¥Ü³æ¤Þ¸¹©ÎÂù¤Þ¸¹®É¡A¥i¥H¥Î( )¸õ²æ¦r¤¸¨Ó±N³o¨â- ӲŸ¹Åã¥Ü¥X¨Ó¡C >>> x='Hello Eric' >>> print x Hello Eric >>> x='Hello, I'm Eric' >>> print x Hello, I'm Eric ¦b°õ¦æÀô¹Ò¤¤¡AµLªk§Q¥ÎEnter¨Óª½±µ´«¦æ¡AYn¶i¦æ´«¦æ¡A¥i¥H¥Î( n )ªº¦r¤¸¨Ó¹F¦¨¡C >>> x='Hello, n I'm Eric' >>> print x Hello, I'm Eric Y¦bµ{¦¡½X¤¤¤@¦¸n¿é¤J¦h¦æ®É¡A¥i¨Ï¥Î( )²Å¸¹¨Ó¹F¦¨¡C >>> x='Hello, ... I'm Eric' >>> print x Hello, I'm Eric ¥t¥~¤]¥i¥H¨Ï¥Î¤TÓ³æ¤Þ¸¹( ''' )©ÎÂù¤Þ¸¹( """ )¨Ó§¹¾ã«O¯d¦r¦ê¸ê®Æªºì©l®æ¦¡¡C >>> x='''Hello, ... I'm Eric''' >>> x "Hello,nI'm Eric" >>> print x Hello, I'm Eric ¦r¦ê¥i¥H¥Î( + )¸¹©ÎªÅ¥Õ¨Ó¹F¨ì¦r¦êªº³sµ²§@¥Î¡A¥t¥~¥i¥H¥Î¼¸¹( * )¨Ó¹F¨ì¿¼Æªº§@¥Î >>> x='Hello, ' >>> y='Eric' >>> print x+y Hello, Eric >>> z='Hello, ' 'Eric' >>> z
  • 4. 'Hello, Eric' >>> print x*5+y*5 Hello, Hello, Hello, Hello, Hello, EricEricEricEricEric ¦ý¨âÓ¦r¦êÅܼƫh¤£¦æ¥ÎªÅ¥Õ¨Ó°µ²Õ¦X¹Bºâ¡A¥²¶·¥Î( + )ªº²Å¸¹¨Ó²Õ¦X¦b¤@°_¡A¥t¥~¦r¦êY- n»P¨ä¥¦«D¦r¦ê«¬ºAªºÅܼƬۥ[¡A¥²¶·n¥ý±N«D¦r¦êªºÅܼƧQ¥Îstr( )¨ç¼ÆÂà ´«¬°¦r¦ê¦A¶i¦æ¹Bºâ¡C >>> z=x y File "<stdin>", line 1 z=x y ^ SyntaxError: invalid syntax >>> z=x+y >>> z 'Hello, Eric' >>> i=9 >>> print i+x Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print str(i)+x 9Hello, Yn¨ú¥X¦r¦ê¤¤¬Y¨Ç¦r¤¸¡A¥i¥H±N¦¹¦r¦êªº¨C¤@Ó¦r¤¸·í¦¨°}¦C¤¤ªº¤¸¯À¡A°_©lªº¦ì¸m¬°¢¯¡C >>> z='Hello, Eric' >>> z[3] 'l' >>> z[0:4] 'Hell' >>> z[:4] 'Hell' >>> z[4:] 'o, Eric' >>> z[-3] 'r' >>> z[0:3]+z[5:] 'Hel, Eric' npºâ¦r¦êªºªø«×¡A¥i¥Îlen( )¨ç¼Æ¨Ópºâ¡C >>> z 'Hello, Eric' >>> len(z) 11
  • 5. ¦r¦êªº©µ¦ù¤Á¤ù¹Bºâ¡A¥i¥H³z¹L²Ä¤TÓ¨îȨӨú¥X¬Û¹jµ¥¶Zªº¦r¦ê¦r¤¸¡C >>> s='abcdefghijklmno' >>> s[1:10:2] 'bdfhj' python ¦r¦êªºUnicode½s½X Unicode¡]¤¤ ¤å¡G¸U°ê½X¡B°ê»Ú½X¡B²Î¤@½X¡B³æ¤@½X¡^¬O¹q¸£¬ì¾Ç»â°ì¸Ìªº¤@¶µ·~¬É¼Ð·Ç¡C¥¦¹ï¥@¬É¤W¤j ³¡¤Àªº¤å¦r¨t²Î¶i¦æ¤F¾ã²z¡B½s½X¡A¨Ï±o¹q¸£¥i¥H¥Î§ó¬°Â²³æªº¤è¦¡¨Ó§e²{©M³B²z¤å¦r¡C ¦bpython 2.7ª©¤¤¡A¹w³]ªº¦r¦ê®æ¦¡¬°ASCII½s½X¡A¦pªG- n¥Hunicodeªº½s½X®æ¦¡¨ÓÀx¦s¦r¦ê¡A¥²¶·¦b¦r¦êªº³Ì«e±¥[¤W 'u' ªº«e¸m¦r¤¸¡A¦p¡G >>> z='Hello, Eric' >>> r=u'Hello, Eric' >>> r u'Hello, Eric' >>> z 'Hello, Eric' >>> chin=u'³o¬O¤@Ó¤¤¤å¦r¦ê' >>> chin u'u9019u662fu4e00u500bu4e2du6587u5b57u4e32' >>> achin='³o¬O¤@Ó¤¤¤å¦r¦ê' >>> achin 'xb3oxacOxa4@xadxd3xa4xa4xa4xe5xa6rxa6xea' >>> print chin ³o¬O¤@Ó¤¤¤å¦r¦ê >>> print achin ³o¬O¤@Ó¤¤¤å¦r¦ê ¹ïunicode½s½Xªº¦r¦ê¦Ó¨¥¡A¨ä«¬¦¡¦p¦P 'uXXXX' ªº®æ¦¡¡A¦UºØ¯S®í²Å¸¹ªºunicode½s½X¡A¥i°Ñ¦Òhttp://www.tamasoft.co.jp/en/general- info/unicode.html¡@¡C >>> a=u'u0040' >>> print a @ python ªºList¸ê®Æ«¬ºA List¸ê®Æ«¬ºA¥i¥H¥Î¨Óªí¥Ü¥ô¦ópython¸ê®Æ«¬ºAªº¦³§Ç¶°¦X¡A¥ç§Y±N¥ô¦ó¸ê®Æ«¬ºAªº¸ê®Æ¦ê ±µ¦b¤@°_¡A¥i¥H¬O¤£¦P¸ê®Æ«¬ºAªº²Õ¦X¡AList¤¤¤]¥i¥H¥]§t¥t¤@ÓList¡A·ín¨ú¥X¨ä¤ ¤ªº¸ê®Æ®É¡A¥i¥H¥ÎÃþ¦ü°}¦Cªº¤è¦¡¡A«ü©wn¨ú¥X¦ì¸mªº¸ê®Æ©Î¤@Ó½d³òªº¸ê®Æ¡A¦p¡G >>> lst=[1,2,'abc',3.4,5+6j] >>> lst [1, 2, 'abc', 3.4, (5+6j)] >>> lst[4] (5+6j) >>> lst[3:] [3.4, (5+6j)] >>> lst[1:3] [2, 'abc'] >>> lst[1:3]=[5,6] >>> lst
  • 6. [1, 5, 6, 3.4, (5+6j)] List¥i¥H³z¹L( + )ªº²Å¸¹¨Ó²Õ¦X¨âÓ¤£¦PªºList¡A¦pªG¬On¥ [¨ì§ÀºÝ¡A«h¥i¥H§Q¥Îappend©Îextend¨âºØ¤èªk¨Ó¹F¦¨¡A¦ý¦¹¨âÓ¤èªk¬O¤£ ¤@¼Ëªº¡A¥i°Ñ¦Ò¤U±¨Ò¤l¡A¤À¿ë¥¦Ìªº¤£¦P¡C >>> x=[1,2,3] >>> y=[4,5,6] >>> z=[a,b,c] Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined >>> z=['a','b','c'] >>> x+y [1, 2, 3, 4, 5, 6] >>> x [1, 2, 3] >>> r=x+y >>> r [1, 2, 3, 4, 5, 6] >>> x.append(y) >>> x [1, 2, 3, 'abc', [4, 5, 6]] >>> x.extend(y) >>> x [1, 2, 3, 'abc', [4, 5, 6], 4, 5, 6] Listªº±Æ§Ç¥i¥H¥Îreverse( )¨ç¼Æ©Î¬O.sort(reverse=True)¨Ó¹F¦¨ >>> x [0, 1, 2, 3, 4, 5] >>> x.sort(reverse=True) >>> x [5, 4, 3, 2, 1, 0] >>> x [5, 4, 3, 2, 1, 0] >>> x.reverse() >>> x [0, 1, 2, 3, 4, 5] List Comprehension¡@ªí¦C¸ÑªR¡A§ÚÌ¥i¥H§Q¥Îfor °j°é¨Ó?¦¨¡C l=[x**2 for x in range(10)] >>> l [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] python ªºtuple¸ê®Æ«¬ºA python ªºtuple¸ê®Æ«¬ºA»PList«D±`Ãþ¦ü¡A¬O¥Î¥ª¥k¨âÓ¬A¸¹ ' ( '»P ' ) '±N¤¸¯À¥]¦b¨ä¤ ¤¡A¨ä»PList³Ì¤jªº®t§O¦b©ó¤@¦ý¨M©w¤F¤¸¯Àªº¤º®e¡A´N¤£¥i¥HÅܧó¡A¤ £¹³List¤@¼Ë¥i¥HÀH®Éקï¡C >>> x=[1,2,3] >>> y=(4,5,6) >>> x[2] 3 >>> y[2] 6
  • 7. >>> x [1, 2, 3] >>> x[2]=99 >>> x [1, 2, 99] >>> y[2]=99 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment pythonªºdict¸ê®Æ«¬ºA ¦bpythonªºListªº¸ê®Æ«¬ºA¤¤¡A¨CÓ¤¸¯À¥H¥¦©Ò¦bªº¦ì¸m§Ç¸¹§@¬°¯Á¤Þ- Èindex¨Ó¶i¦æ¸ê®Æ¦s¨úªºkeyÈ¡A¦bdictªº¸ê®Æ«¬ºA¡A«h¬O¥i¥H¦Û©wkeyȨӰµ¬°¸ê®Æªº¯Á¤Þ- È¡C dict¸ê®Æ«¬ºA¬O¥Î¥ª¥k¤j¬A¸¹ ' { ' ¡B' } ' ±N¸ê®Æ¥]§t¦b¨ä¤¤¡A¨Ã¥Î³r¸¹ ' , ' ¨Ó§@¬°°Ï¹j¡A¨CÓkey-value¬O¥H«_¸¹ ' : ' ¨Ó¶i¦æ°t¹ï¡A¦p¡G >>> dic={'name':'eric','phone':'0900000000','email':'a@b.c.d'} >>> dic {'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'} dict¸ê®Æ«¬ºAªºkeyȤ@©wn¬O¦r¦ê¸ê®Æ¡AvalueÈ«h¥i¥H¬O¥ô¦ó¸ê®Æ«¬ºA¡C dict¤]¥i¥H¥ÑListªº°t¹ïtuple¸ê®ÆÂà´«¦Ó¨Ó¡A¨ä¤¤tuple²Ä¤@Ó¤¸¯À·|Âà´«¬°key¡A²Ä¤G- Ó¤¸¯À·|Âà´«¦¨value >>> x=[('name','eric'),('phone','0900000000'),('email','a@b.c.d')] >>> y=dict(x) >>> y {'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'} >>> y['phone'] '0900000000' ¥t¥~¤]¥i¥H¥Îzipªº¤è¦¡±N¨âÓ¦P¼Æ¶q¤£¦PListÂà´«¦¨¤@Ódict¸ê®Æ«¬ºA¡A¦p¡G >>> x=['name','phone','email'] >>> y=['eric','0900000000','a@b.c.d'] >>> z=zip(x,y) >>> z [('name', 'eric'), ('phone', '0900000000'), ('email', 'a@b.c.d')] >>> dict(z) {'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'} >>> z [('name', 'eric'), ('phone', '0900000000'), ('email', 'a@b.c.d')] >>> r=dict(z) >>> r {'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'} ¥t¥~¡A§Ṳ́]¥i¥H±NdictÂà´«¦¨Listªº¸ê®Æ«¬ºA¡C >>> t=r.items() >>> t [('phone', '0900000000'), ('name', 'eric'), ('email', 'a@b.c.d')] Y§ÚÌn¨ú¥Xdictªºkey©ÎvalueȮɡA¥i¥H¨Ï¥Îkeys( )¤Îvalues( )¨âÓ¤èªk¨Ó¨ú¥X¡A¦p >>> r {'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'} >>> r.keys()
  • 8. ['phone', 'name', 'email'] >>> r.values() ['0900000000', 'eric', 'a@b.c.d'] Yn§R°£¬Y¤@¹ïkey-value²Õ¦X®É¡A¥i¥H¨Ï¥Îdel«ü¥O¡A¦p¡G >>> r {'phone': '0900000000', 'name': 'eric', 'email': 'a@b.c.d'} >>> del r['name'] >>> r {'phone': '0900000000', 'email': 'a@b.c.d'} python ªº¥¬ªL¸ê®Æ«¬ºA»PªÅÈ python ¤¤nªí¥Ü¥¬ªL¸ê®Æ«¬ºA¡A¥i¥H¨Ï¥ÎTrue¤ÎFalse¨Óªí¥Ü¡A¦b±±¨î¬yµ{¤¤¡A·|¨Ï¥Î¥¬ªL- ȨӧPÂ_¬O§_¶i¤J°j°é¡C >>> t=True >>> type(t) <type 'bool'> >>> r=False >>> r False Noneªí¥ÜÅܼƬOªÅÈ¡A¨ä¬Û·í©óJavaªºnull¡C >>> x ['name', 'phone', 'email'] >>> x=None >>> x python ªº¬yµ{±±¨î python ¦b°õ¦æµ{¦¡®É¡A³£¬O¨Ì·Óµ{¦¡½Xªº¶¶§Ç¥Ñ¤W¦Ó¤U°õ¦æ¡AY¹J¨ìµ{¦¡»Ýn°µ§PÂ_¡B©Î»Ý- n¤ÏÂаõ¦æ¬Y´X¦æµ{¦¡½X®É¡A´N»Ýn§ïÅܵ{¦¡°õ¦æªº¬yµ{¡C if ±ø¥ó§PÂ_¦¡ ·í»Ýn°µ±ø¥ó§PÂ_®É¡A´N¥²¶·¨Ï¥Î if ªº±ø¥ó§PÂ_¡A¦p¡G >>> x=30 >>> if x>30: ... print 'x is more than 30.' >>> elif x==30: ... print 'x is equal to 30.' >>> else: ... print 'x is small than 30.' >>> ... x is equal to 30. if ªº±ø¥ó§PÂ_¥i·f°t elif ¤Î else ¨Ó§PÂ_¨ä¥¦ªº±ø¥ó¡C¨C¤@ӲŦX±ø¥óªº°Ï¶ô¥H "¡G" ¶}©l¡A¥i¥H¥ÎÁY±Æ¨Ó°Ï¤À¡A¦ý¦P¤@°Ï¬qªºÁY±Æ¤è¦¡n¤@P¡C if / else ¤T¤¸¹Bºâ¦¡ >>> if X: ... A=Y
  • 9. >>> else: ... A=Z >>> x=1 >>> if x: ... a=2 ... else: ... a=3 ... >>> a 2 >>> b=2 if x else 3 >>> b 2 >>> x=0 >>> b=2 if x else 3 >>> b 3 >>> if <±ø¥ó1 > : ... #±Ôz1 >>> elif < ±ø¥ó2 > : ... #±Ôz2 >>> else : ... #±Ôz while °j°é ¦pªG§Æ±æ¤ÏÂаõ¦æ¬Y¤@¬qµ{¦¡½X¡Aª½¨ì¹F¦¨¬Y±ø¥ó«á¤~µ²§ô®É¡A¥i¥H¨Ï¥Î while °j°é¡C >>> i=0 >>> while i<10: ... print i ... i+=1 ... 0 1 2 3 4 5 6 7 8 9 for °j°é ¦pªGn°w¹ï¤@Ó list ªº¸ê®Æ½d³ò§@°j°é¡A¥i¥H¨Ï¥Îfor °j°é¡A·í¨C¦¸°õ¦æ®É¡A´N·|¨Ì§Ç±q list ¤¤¨ú¥X¤@Ó¤¸¯À¨Ó³B²z¡C >>> x=range(10) >>> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for i in x: ... print i ... 0 1 2 3
  • 10. 4 5 6 7 8 9 Y list ¤¤ªº¸ê®Æ¬O list ©Î tuple¸ê®Æ«¬ºA®É¡A¤]¥i¥H¨Ï¥Îfor °j°é¨Ó¨ú¥X¹ïÀ³ªº¤¸¯À¡A¦p¡G >>> dic={'name':'eric','email':'eric@gmail.com'} >>> for k,v in dic.items(): ... print 'dic[%s]=%s'%(k,v) ... >>> dic[name]=eric >>> dic[email]=eric@gmail.com >>> break?z·|¥ß§Y¸õÂ÷°j°é while °j°é¥i¥H·f°tbreak ¨Ó¤¤Â_©Î©¿²¤¬Y¤@³¡¥÷ªºµ{¦¡°j°é¡C >>> i=0 >>> while i<10: ... if i==5: break ... print i ... i+=1 ... 0 1 2 3 4 continue?z·|¸õ¦Ü³Ìªñ©Ò¦bªº°j°é §Y·í¦¸¤£°µ¡A¨Ó¨ì°j°é¶}ÀY¦C¡AÄ~Äò¤U¤@¦¸ >>> x=10 >>> while x: ... x-=1 ... if x%2!=0: continue ... print x ... 8 6 4 2 0 pass ?z¬O¤°»ò¨Æ¤]¤£°µ¡AÄ~Äò°õ¦æ¤U¤@Ó?z¡C >>> while 1: ... pass ... n«öctrl-C¤~·|°±¤î¡C try?z ·íµ{¦¡¦³¥i¯à°õ¦æ®É¥X²{¨Ò¥~¿ù»~¨Æ¥ó®É¡A§ÚÌ¥i¥H¨Ï¥Îtryªº±±¨î¶µ±Nµ{¦¡¥]§t¦b¨ä¤¤ ¡A¨ä¥Îªk¦p¤U¡G¡@ >>> while True: ... reply=raw_input('Enter number:') ... if reply=='stop': break ... try: ... num=int(reply)
  • 11. ... except: ... print 'Bad!'*8 ... else: ... print int(reply)**2 ... print 'Bye' °õ¦æµ²ªG¡G python trySample.py Enter number:8 64 Enter number:9 81 Enter number:ee Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad! Enter number:i Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad! Enter number:stop Bye example : ¦p¦ó¥Îfor¤Îif/elseªº§PÂ_¦¡¡A¼g¥X¤U¦C¹Ï¥Ü * *** ***** ******* ***** *** * Ans: >>> intMaxSize=7 ... for i in range(1,intMaxSize*2+1,2): ... if i>intMaxSize: print '*'*(intMaxSize-(i-intMaxSize)) ... else: print '*'*i is ¥Îªk >>> 'abc' is 'qoo' False is not ¥Îªk >>> 'banana' is not 'apple' True in ¥Îªk >>> 'a' in 'apple' True ¯S®í¦r¤¸ d # ¼Æ¦r = [0-9] D # «D¼Æ¦r =[ ^0-9 ] s # ªÅ¥Õ¦r¤¸ = [ tnrfv] S # «DªÅ¥Õ¦r¤¸ = [^ tnrfv] w # ¦r¥À»P¼Æ¦r =[0-9a-zA-Z] W # «D¦r¥À»P¼Æ¦r = [^0-9a-zA-Z]
  • 12. µ{¦¡½d¨Ò1 # * = {0,} = 0~µL¦¸ >>> import re >>> print(re.findall('ab*', '1add2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0~n >>> print(re.findall('ab*', '1aabbbbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0~n >>> print(re.findall('ab{0,}', '1babbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0~n >>> print(re.findall('1[D]*', '1abc2')) # ´M§ä1¶}ÀY¡A«á- ±«D¼Æ¦rªø«×¬°0~n >>> print(re.findall('1*c', '1abc2')) # ´M§ä1ªø«×¬°0~n¡A«á±¥X²{c ['a'] ['a', 'abbbbb'] ['abbb'] ['1abc'] ['c'] µ{¦¡½d¨Ò2 # + = {1,} = 1~µL¦¸ >>> import re >>> print(re.findall('ab+', '1add2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°1~n >>> print(re.findall('ab+', '1aab2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°1~n >>> print(re.findall('ab{1,}', '1babbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°1~n >>> print(re.findall('1[D]+', '1abc2')) # ´M§ä1¶}ÀY¡A«á- ±«D¼Æ¦rªø«×¬°0~n >>> print(re.findall('w+', '1abc2')) # ´M§ä¦r¥À»P¼Æ¦r¡Aªø«×¬°1~n >>> print(re.findall('[a-b1]+', '1abc2')) # ´M§ä¦r¥Àa-b©Î1¡Aªø«×¬°1~n [] ['ab'] ['abbb'] ['1abc'] ['1abc2'] ['1ab'] µ{¦¡½d¨Ò3 # ? = {0,1} = 0©Î1¦¸ >>> import re >>> print(re.findall('ab?', '1add2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0©Î1 >>> print(re.findall('ab?', '1aab2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0©Î1 >>> print(re.findall('ab?', '1babbb2')) # ´M§äa¶}ÀY¡A«á±bªø«×¬°0©Î1 >>> print(re.findall('1[D]?', '1abc2')) # ´M§ä1¶}ÀY¡A«á- ±«D¼Æ¦rªø«×¬°0©Î1 >>> print(re.findall('[a-b]', '1abc2')) # ´M§äa©Îb ['a'] ['a', 'ab'] ['ab'] ['1a'] ['a', 'b'] µ{¦¡½d¨Ò4 # ^ = ¦r¦êªº¶}ÀY (¥Î¦b¤¤¬A¸¹¤ºªº¤~¬O "«D" [^ ]) >>> import re >>> print(re.findall('^a', 'abc123')) # ¥Ha¬°¶}ÀYªº¦r >>> print(re.findall('^1', 'abc123')) # ¥H1¬°¶}ÀYªº¦r >>> print(re.findall('^D', 'abc123')) # «D¼Æ¦r¶}ÀYªº¦r >>> print(re.findall('^[D]+', 'abc123')) # «D¼Æ¦r¶}ÀY¡Aªø«×¬°1~n¦¸ >>> print(re.findall('^w+', 'abc123')) # ¦r¥À©Î¼Æ¦r¶}ÀY¡Aªø«×¬°1~n¦¸ ['a'] [] ['a'] ['abc'] ['abc123'] µ{¦¡½d¨Ò5 # $ = ¦r¦êªºµ²§À >>> import re >>> print(re.findall('1$', 'abc123')) # ¥H1µ²§Àªº¦r >>> print(re.findall('3$', 'abc123')) # ¥H3µ²§Àªº¦r >>> print(re.findall('d$', 'abc123')) # ¥H¼Æ¦rµ²§Àªº¦r >>> print(re.findall('d+$', 'abc123')) # ¥H¼Æ¦rµ²§Àªº¦r¡Aªø«×¬°1~n >>> print(re.findall('[w]+$', 'abc123')) # ¦r¥À©Î¼Æ¦rµ²§À¡Aªø«×¬°1~n [] ['3'] ['3'] ['123'] ['abc123'] ¨ç¦¡¡Gfindall() ´M§ä¥þ³¡ >>> import re >>> text = 'shdfluihnlsdgjlsrfjileghluiesrgl3h42h3583593hu6i4h32896h3896h2436jl423j84936j23 l4jt4lfff9m39m39f' >>> pwd = re.findall('d',text) >>> print(pwd) ['3', '4', '2', '3', '5', '8', '3', '5', '9', '3', '6', '4', '3', '2', '8', '9',
  • 13. '6', '3', '8', '9', '6', '2', '4', '3', '6', '4', '2', '3', '8', '4', '9', '3', '6', '2', '3', '4', '4', '9', '3', '9', '3', '9'] python ¨ç¦¡³B²z ·í¦³¤@¬qµ{¦¡½X»Ýn«Âаõ¦æ®É¡A§ÚÌ¥i¥H±N¦¹¬qµ{¦¡½X©w¸q¦¨¤@Ө禡(function) ¡A¥H§Q§@¬°«áÄò©I¥s¨Ï¥Î¡C ¨ç¦¡ªº©w¸q §ÚÌ¥i¥H³z¹Ldef ªº¤è¦¡¨Ó©w¸q¨ç¦¡¦WºÙ def <name>(arg1,arg2,.....,argN): <statements> Y¦³¦^¶ÇÈ¡A¥i©w¸q¬° def <name>(arg1,arg2,.....,argN): <statements> return <vaule1,value2,.....,valueN) ¦p¡G >>> def plusAndMulti(x,y): ... intPlus=x+y ... intMulti=x*y ... print 'x+y=%s'%intPlus ... print 'x*y=%s'%intMulti >>> plusAndMulti(10,20) x+y=30 x*y=200 >>> def getPlusResult(x,y): ... return x+y >>> getPlusResult(10,20) 30 >>> def getFirstAndLastElement(lst): ... if not len(lst)>0: return None,None ... return lst[0],lst[len(lst)-1] >>> lst=[1,2,3,4,5] >>> getFirstAndLastElement(lst) (1, 5) >>> lst=[5] >>> getFirstAndLastElement(lst) (5, 5) >>> lst=[] >>> getFirstAndLastElement(lst) (None, None) >>> lst=[1,2,3,4,5] >>> b,c=getFirstAndLastElement(lst) >>> print b,c 1 5 ¨ç¦¡¹w³]°Ñ¼ÆÈ ¦b©w¸q¨ç¦¡®É¡A§ÚÌ¥i¥H³]©w°Ñ¼Æªº¹w³]È¡A·í©I¥s¨ç¦¡®É¨S¦³±a¤J¦¹°Ñ¼Æ®É¡A¨t²Î´N·| ¥H¹w³]ªº°Ñ¼ÆȨӴÀ¥N¡C >>> def getPlusResult(x,y=5):
  • 14. ... return x+y >>> getPlusResult(4) 9 ª`·N¡G·í°Ñ¼Æ¬O¤@Ó½ÆÂøªº¸ê®Æµ²ºc®É(«D¼Æ¦r©Î¦r¦ê)¡A¸ê®Æ¤º®e¥i¯à·| ¦]¬°²Ö¿n®ÄÀ³¦ÓÁ׶}¤F¹w³]Ȫº³]©w¡C¦p¡G >>> def appendList(x,y=[]): ... y.append(x) ... return y >>> appendList(3) [3] >>> appendList(4) [3, 4] >>> appendList(5) [3, 4, 5] ¨Ï¥ÎÃöÁä¦r¶ñ¤J°Ñ¼ÆÈ ·í©w¸q¨ç¦¡»Ýn¶Ç¤J¦hӰѼÆȮɡA°£¤F¥i¥H«ö¶¶§Ç¶ñ¤J°Ñ¼ÆÈ¥H¥~¡A¤] ¥i¥H¨Ï¥Î«ü©w°Ñ¼Æ¦WºÙ¨Ó¶ñ¤J°Ñ¼ÆÈ¡A¦p¦¹´N¥i¥H¤£¥²¨Ì·Ó¶¶§Ç¤F¡C >>> def getGreeting(greeting,name='anonymous',postfix='.'): ... return '%s, %s%s'%(greeting, name, postfix) >>> getGreeting('Hello',postfix='?') 'Hello, anonymous?' >>> getGreeting('Hi','Gina','~') 'Hi, Gina~' >>> getGreeting(postfix='!',name='Tina',greeting='Yo') 'Yo, Tina!' ª`·N¡G¦b¨ç¼Æ©w¸q®É¡A¾¨¥i¯à±N¨S¦³¹w³]- Ȫº°Ñ¼Æ±Æ¦b¥ª°¼¡A¥H«K¦b¥¼«ü©w°Ñ¼Æ¦WºÙ®É¡A¨t²Î¯à¹ïÀ³¨ì¥¿½Tªº°Ñ¼Æ¡C ¤£©wÓ¼Æ°Ñ¼Æ ·í§A¦b¦Ò¼{¨ç¦¡®É¡AYµLªk½T©w¥i¯à±a¤J°Ñ¼ÆªºÓ¼Æ®É¡A¥i¥H¦b©w¸q¨ç¦¡®É¨Ï¥Î '*' ¥Nªí¤ £©wӼưѼƨөw¸q¨ç¦¡°Ñ¼Æ¡C >>> def getMultiGreeting(greeting, *name): ... multiName=','.join(name) ... print '%s'%type(name) ... return '%s: %s'%(greeting,multiName) >>> getMultiGreeting('Hello','eric','Tina','Gina') <type 'tuple'> 'Hello: eric,Tina,Gina' >>> getMultiGreeting('Hello','eric','Tina','Gina','Tom','David') <type 'tuple'> 'Hello: eric,Tina,Gina,Tom,David' ª`·N¡G¥Ñ '*' ©Ò©w¸qªº°Ñ¼Æ¬O¥Htuple«¬ºA¦s¦b¡A¦]¦¹¥i¥H§â¥¦·ítuple¨Ó¾Þ§@¥¦¡C Y¨Ï¥Î '**' ¨Ó©w¸q°Ñ¼Æ¡A«h¥i¥H§â¥¦·í¦¨dictªº¸ê®Æ«¬ºA¾Þ§@¥¦¡C¦p¡G >>> def getUsersNameEmail(name,**options): ... print 'StudentName:%s'%name ... if options.has_key('age'): print 'Age:%s'%options['age']
  • 15. ... if options.has_key('email'): print 'Email:%s'%options['email'] >>> getUsersNameEmail('eric',age=17,email='laaa@hinet.net') StudentName:eric Age: 17 Email: laaa@hinet.net ¨ç¦¡¡Gsub() ¨ú¥N # re.sub() >>> import re >>> pwd = re.sub('D','',text) #¤£¬O¼Æ¦rªº¨ú¥N¦¨ªÅ¦r¦ê >>> print (pwd) 342358359364328963896243642384936234493939 ¨ç¦¡¡Gjoin() ¦ê³slist >>> tmp = re.findall('d', text) # ¬D¥X«D¼Æ¦r¡A²Õ¦¨list >>> pwd = ''.join(tmp) # ±N¦ê¦C³s±µ°_¨Ó¡A¤¤¶¡¤ £¶ë¥ô¦ó¸ê®Æ >>> print (pwd) 8784709893727894859089 Python ªºª«¥ó³]p ¦bpython ¤¤°£¤F¥i¥H©w¸q¨ç¦¡¥~¡A¥¦¤]¦P¼Ë¦³ª«¥ó¾É¦Vªº³]- p¡AclassÃöÁä¦r«h¬O¥Î¨Ó©w¸qª«¥óªºÃþ§O¡Aª«¥óÃþ§O¥i¥H¥Î¨Ó²£¥Íª«¥ó¹êÅé ( instance) ¡A©Ò¥H¥¦¤]¥i¥Hµø¬°¬O¤@ºØ¸ê®Æ«¬ºA¡C >>> class Student(object): ... number='' ... def __init__(self,number): ... self.number=number ... def set_number(self,number): ... self.number=number ... def get_number(self): ... return self.number >>> std=Student('') >>> print std.get_number() >>> std=Student('N90000001') >>> print std.get_number() N90000001 >>> std.set_number('N00010001') >>> print std.get_number() N00010001 Studentª«¥óÃþ§O¤U©w¸q¤F " __init__"¡B" set_number"¡B"get_number"¤TӨ禡¡A¨C¤@- Ө禡ªº²Ä¤@ӰѼƳ£¥²¶·¬Oself¡A¬O¥Î¨Ó¥Nªí©I¥s¦¹¨ç¦¡ªºª«¥ó¹êÅé¡C number¬O¦¹ª«¥óªºÄÝ©Ê(attribute)¡A set_number»Pget_number¬O¦¹ª«¥óªº¤èªk(method)¡A __init__¤èªk¬Oª«¥óªº«Øºc¤l(constructor)¡A¬O¦b«Ø¥ßª«¥ó¹êÅé®É¨t²Î¹w³]©I¥sªº¨ç¦¡¡A ¦b¤Wz¨Ò¤l¤¤«Ø¥ßstd=Student('N90000001')ª«¥óstd®É¡A ´N¬O¹ïÀ³¨ìª«¥óÃþ§O¤Uªº__init__¨ç¦¡¡A'N90000001'«h¬O¹ïÀ³¨ìnumber°Ñ¼Æ- È¡Aset_number»Pget_numberªº¤èªk¦bª«¥ó²£¥Í®É ´N¥i¥Hª½±µ¨Ï¥Î¡AÃþ¦ü©ójava»y¨¥ªºpublic¤èªk¡A¦p std.set_number('N00010001') ¡Bstd.get_number()¡C Ãþ§O©w¸q§¹¦¨«á¡A¥i¥H¥Î¨Ó²£¥Í³¦hªºª«¥ó¹êÅé¡A¦Uª«¥ó¹êÅ鶡¨Ã¤£·|¤¬¬Û¼vÅT¡C
  • 16. >>> s1=Student('N99010001') >>> s2=Student('N99020002') >>> s3=Student('N99030003') >>> print s1.get_number() N99010001 >>> print s2.get_number() N99020002 ¥t¥~¡A¦b¤Wzªº¨Ò¤l¤¤¡AnumberÄݩʤ]¬OÄÝ©ópublicªºÄÝ©Ê¡Aª«¥ó¥i¥Hª½±µ§ïÅÜnumberªºÈ¡C >>> s1.number='N99040004' >>> print s1.get_number() N99040004 Y¤£·QnÅýÄݩʩΤèªk¥i¥Hª½±µ³Q®³¨Ó¨Ï¥Î¡A§ÚÌ¥i¥H§Q¥Î¨âÓ©³½u " __"§@¬°«e¸m¦r¦ê¡A¨Ó±N¥¦ÌÁôÂð_¨Ó¡AÃþ¦üjava»y¨¥ªºprotected©Îprivate¥Îªk¡C >>> class Student(object): ... __number='' ... def __init__(self,number): ... self.__number=number ... self.__initSomething() ... def set_number(self,number): ... self.__number=number ... def get_number(self): ... return self.__number ... def __initSomething(self): ... print 'init something....' >>> s1=Student('N99010001') init something.... >>> s1.__name Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute '__name' >>> s1.__initSomething() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute '__initSomething' >>> s1.get_number() 'N99010001' ¦ý¹ï©ó¤F¸Ñpython»y¨¥ªÌ¦Ó¨¥¡A¨ä¹ê³oºØ¤è¦¡¥u¬O±N³o¨Ç¤èªk¤ÎÄÝ©Ê´«Ó¦W¤l¦Ó¤w¡AY¯u- n©I¥s¥¦Ì¡A¤´µM¬O¥i¥H°µ±o¨ì¡A¥u¬On¦h¤@¹Dµ{§Ç¦Ó¤w¡A§Y¦b¤èªk©ÎÄݩʪº«e±¥[¤W " _ª«¥óÃþ§O¦WºÙ" ¤~¯àª½±µ¦s¨ú¡C©Ò¥H¡A¥u¦³±oª¾Ãþ§O¦WºÙªº¤~¯àª½±µ¦s¨ú±o¨ì¡A³o¼ËÁÙ¬O¥i¥H°µ¨ì°ò¥»ªº¸ê °TÁôÂáC >>> s1._Student__number 'N99010001' >>> s1._Student__initSomething() init something.... python ªºª«¥óÄ~©Ó ª«¥óªºÄ~©ÓÃö«Y( inheritance)¡A¥i²¤ÆÁc½Æ³]- pªºµ{¦¡½X¡AÅýª«¥ó«O¯d¥Àª«¥óªºÄݩʤΤèªk¡A¨Ã¥i¥H¥[¤W©Î- קï¦Û¤vªºÄÝ©Ê»P¤èªk¡A³oºØ¤è¦¡¤j¤j´£°ªµ{¦¡³]pªº®Ä²v¡AÄ~©Óªº¤èªk ´N¬O¦bª«¥óÃþ§O¦WºÙ«áªº¤p¬A¸¹¤¤¡A©ñ¤J-
  • 17. nÄ~©Óªºª«¥óÃþ§O¦WºÙ(¦pStudentª«¥óÃþ§OÄ~©Ó¤Fobjectª«¥ó¡C >>> class Student(object): ... number='' ... def __init__(self,number): ... self.number=number ... self.__initSomething() ... def set_number(self,number): ... self.number=number ... def get_number(self): ... return self.number ... def __initSomething(self): ... print 'init something....' >>> class TimeWorker(Student): ... __name='' ... def __init__(self,number,name): ... self.number=number ... self.__name=name ... def set_name(self,name): ... self.__name=name ... def get_name(self): ... return self.__name >>> tw=TimeWorker('N95050005','eric') >>> tw.get_number() 'N95050005' >>> tw.get_name() 'eric' ª`·N¡GY¬On³QÄ~©Óª«¥ó¤¤ªº¦¨û®É¡A¥i¨Ï¥Îsuper( )¤èªk©I¥s¥ÀÃþ§O¤èªk©ÎÄÝ©Ê¡A¦p- n©I¥s¥ÀÃþ§Oªº__init__³]©w«Øºc¤l¡A©ñ¤Jªì©lÈ¡C >>> class Student(object): ... __number='' ... def __init__(self,number): ... self.__number=number ... self.__initSomething() ... def set_number(self,number): ... self.__number=number ... def get_number(self): ... return self.__number ... def __initSomething(self): ... print 'init something....' >>> class TimeWorker(Student): ... __name='' ... def __init__(self,number,name): ... super(TimeWorker,self).__init__(number) ... self.__name=name ... def set_name(self,name): ... self.__name=name ... def get_name(self): ... return self.__name >>> tw=TimeWorker('N95050005','eric') init something.... >>> tw.get_number() 'N95050005' python ªºÀɮ׳B²z
  • 18. python n¶}±ÒÀɮ׮ɡA¥i©I¥s¤º«Øªº¨ç¦¡ open(filename, mode)¡Amode¦³¦hºØ¿ï¾Ü¡G 'r' ¡G ¶}±ÒÀɮ׬°Åª¨ú¼Ò¦¡¡A¦¹¬°¹w³]¼Ò¦¡¡C 'w'¡G¶}±ÒÀɮ׬°¥i¼g¤J¼Ò¦¡¡AYÀɮצs¦b¡A«h·|³QÂл¤º®e¡C 'a'¡G¶}±ÒÀɮ׬°¥i¶i¦æ§ÀºÝªþ¥[¼g¤J¼Ò¦¡¡C 'b'¡GÀɮ׶i¦æ¤G¶i¦ì¸ê®Æ³B²z °Ñ¦Ò¸ê®Æ¡Ghttps://docs.python.org/2/tutorial/inputoutput.html#reading-and- writing-files ÀÉ®×¼g¤J¼Ò¦¡ >>> f = open('workfile', 'w') >>> f.write('This is the entire file.n') >>> print f <open file 'workfile', mode 'w' at 0x020C4D88> >>> f.close() ÀÉ®×Ū¨ú¼Ò¦¡ >>> myfile=open('workfile') >>> myfile.readline() 'This is the entire file.n' >>> myfile.readline() '' >>> f= open("rw_test", "w") # w¥Nªí¼g¤J¡Aw+«h¬O¨S¦³Àɮתº¸Ü·|¦Û°Ê·s¼W >>> f.write("Hello 123") >>> f.close() >>> f = open ("rw_test", "r") # r¥NªíŪ¨ú >>> f.read() 'Hello 123' Àɮתþ¥[¼g¤J¼Ò¦¡ >>> f = open('workfile', 'a') >>> f.write('Second line of the filen') >>> f.close() >>> myfile=open('workfile') >>> myfile.readline() 'This is the entire file.n' >>> myfile.readline() 'Second line of the filen' >>> myfile.readline() '' >>> data=open('workfile').read() >>> print data This is the entire file. pythonªº¨Ò¥~³B²z ·ípythonªºµ{¦¡½X¦b°õ¦æ®É¡AYµo¥Í»yªk©Îµ{¦¡¹Bºâ¿ù»~®É¡A¨t²Î´N·|¥á¥X¤@- Ó¨Ò¥~(Exception)¿ù»~¡A¦p¡G >>> i=0 >>> 10/i Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero >>> whild i<10: print i File "<stdin>", line 1 whild i<10: print i ^
  • 19. SyntaxError: invalid syntax ¤Wz¨Ò¤l´N¬O·í¸ê®Æ«¬ºA©Î»yªk¿ù»~®É¡Apython ª½Ä¶¾¹´N·|? ¥X(throw)ZeroDivisionError¤ÎSyntaxErrorªº¿ù»~¡A¦pªG¨S¦³¦n¦n³B²z¡Aµ{¦¡´N·|¤ ¤Â_¦b¦¹¡AµLªk«ùÄò¶i¦æ¡C §ÚÌ¥i¥H°w¹ï¯S©wªº¨Ò¥~¿ù»~¨Ó«Ø¥ß±µ¦¬¿ù»~³B²zªºµ{¦¡°Ï¬q >>> try: ... n=10/0 ... print n ... except ZeroDivisionError: ... print 'Davided by 0' ... Davided by 0 ¦¹§Y·í§Ú̹w´Áªº¿ù»~µo¥Í®É¡A´N¥i¥H³z¹L¨Æ«e³]p¦nªº³W«h¨Ó³B²z¬Û¹ïÀ³ªº¿ù»~±¡ªp¡C ¦pªG§A³]pªºµ{¦¡°Ï¶ô¦³¥i¯àµo¥Í³¦h¦UºØ¤£¦Pªº¨Ò¥~±¡ªp¡A§A¥i¥H¨Ï¥Î¦hÓ¤ £¦Pªºexcept¨Ó³B²z©Î¬O¨Ï¥Îelse¨Ó³B²z¨ä¥L¨S¦³³B²z¨ìªº¨Ò¥~ª¬ªp¡C >>> try: ... readFile=open('testFile.txt','r') ... firstLine=readFile.readline() ... intNum=int(firstLine) ... print intNum ... except IOError: ... print 'Error on opening file or reading first line.' ... except ValueError: ... print 'Cannot convert first line to integer.' ... else: ... print 'Unknow Error' ... finally: ... print 'finally....' YÀɮפ£¦s¦b¡A«h·|¥X²{ Error on opening file or reading first line. finally.... YÀɮצs¦b¡A¦ý¤º®eµLªkÂà´«¦¨¾ã¼Æ®É Cannot convert first line to integer. finally.... ¦pªG¨S¦³µo¥Í¨Ò¥~¡A°£¤F·|°õ¦æ¥Xµ²ªG¥~¡Aelseªº¤º®e¤]·|°õ¦æ ... 45 Unknow Error finally.... finally?zªº¤º®e«h¬O¤£ºÞ°õ¦æµ²ªG¥¿±`©Î¬Oµo¥Í¨Ò¥~®É¡A¥¦³£·|Â÷¶}try¤§«e°õ¦æ¡C ¥t¥~¡A§Ṳ́]¥i¥H±N¿ù»~°T®§Åª¨ú¥X¨Ó¡A¦p¡G >>> try: ... readFile=open('testFile1.txt','r') ... firstLine=readFile.readline() ... intNum=int(firstLine) ... print intNum ... except Exception as ex: ... print 'Error message is %s'%ex ... else: ... print 'Unknow Error' ... finally:
  • 20. ... print 'finally....' ... Error message is [Errno 2] No such file or directory: 'testFile1.txt' finally.... python ¦Ûq¨Ò¥~³B²z ¦bµ{¦¡½X¤¤¡AY¯à¹w´ú·|µo¥Íªº¨Ò¥~±¡§Î¡A§A´N¥i¥H¨Ï¥ÎraiseÃöÁä¦r¨Ó¤â°Ê?¥X¤@- Ó¨Ò¥~ª«¥ó¡C >>> def getDivisionResult(intNum1,intNum2): ... if not intNum2: ... raise ZeroDivisionError('Number 2 can not be zero') ... else: ... return intNum1/intNum2 >>> try: ... getDivisionResult(10,0) ... except ZeroDivisionError as err: ... print 'Error Message is %s'%err ... Error Message is Number 2 can not be zero >>> >>> try: ... getDivisionResult(10,5) ... except ZeroDivisionError as err: ... print 'Error Message is %s'%err ... 2 >>> ¦UºØ«¬¦¡ªºerror ª«¥ó¡A¥i°Ñ¦Ò¡Ghttps://docs.python.org/2/library/exceptions.html ¥t¥~¡A§Ṳ́]¥i¥H¦Û¦æ©w¸q¨Ò¥~ª«¥ó¡A¦Û¦æ©w¸qªºª«¥ó¡A¥²¶·nÄ~©Ó¦ÛExceptionª«¥óÃþ§O¡C >>> class DivisionErr(Exception): ... def __init__(self,msg): ... self.message=msg >>> def getDivisionResult(intNum1,intNum2): ... if not intNum2: ... raise DivisionErr('Number 2 can not be zero') ... else: ... return intNum1/intNum2 >>> try: ... getDivisionResult(10,0) ... except DivisionErr as err: ... print err.message ... Number 2 can not be zero Y§A·Q- nÅý§A©w¸qªºª«¥ó¹êÅé¹³¤@¯ë±`¨£¨ìªº¨Ò¥~ª«¥ó¤@¼Ë¡A¯à°÷ª½±µ³z¹Lª«¥ó¹êÅé¨Ó¿é¥X®É¡A§A¥ ²¶·¦bª«¥ó¤¤¥[¤J __str__ ªºª«¥ó¤èªk¡C >>> class DivisionErr(Exception): ... def __init__(self,msg): ... self.message=msg ... def __str__(self):
  • 21. ... return self.message >>> def getDivisionResult(intNum1,intNum2): ... if not intNum2: ... raise DivisionErr('Number 2 can not be zero') ... else: ... return intNum1/intNum2 >>> try: ... getDivisionResult(10,0) ... except DivisionErr as err: ... print 'Error message is %s'%err ... Error message is Number 2 can not be zero python ªº¼Ò²Õ³]p ¦bÀ³¥Îµ{¦¡¶}µoªº¹Lµ{¤¤¡A§ÚÌ·|±N¬ÛÃöªº¨ç¦¡©ÎÃþ§Oµ{¦¡½X²Õ¦X¦b¦P¤@¤äµ{¦¡¡A³oÓ§Ú- ̺٤§¬°¼Ò²Õ¡A·í³oÓ¼Ò²Õ»Ýn³Q¨ä¥¦µ{¦¡¤Þ¥Î®É¡A¥i¥H¨Ï¥Îimport ªº«ü¥O¨Ó±N¼Ò²Õ¤Þ¤J¡A¸g±`¤@ÓÀ³¥Îµ{¦¡¬O¥²¶·n¤Þ¥Î¦h- Ó¼Ò²Õmodule¤~¯à§¹¦¨À³°õ¦æªº¥ô°È¡C ¹ï¨C¤@ÓpythonÀɮצӨ¥¡A§Ṳ́]¥i¥H±N¥¦µø¬°¤@Ó¼Ò²Õ¡A¨Ò¦p¡A§Ú̦bmyMathFun.pyÀɮפ ¤³]p¤@Ó¥i¥Hpºâ¶¥¼h¥[Á`ªº¨ç¦¡¡G >>> # myMathFun.py >>> def sumHierarchy(n): ... if n<2: return 1 ... else: return n+sumHierarchy(n-1) ¦pªGn¦b¨ä¥¦ªºµ{¦¡¤¤°õ¦æ¡A´N¥²¶·§Q¥Îimport ªº»yªk©Îfrom xxx import xxxªº»yªk±N¼Ò²Õ©Î¼Ò²Õ¤¤ªº¨ç¦¡¤Þ¤J¡G >>> # main.py >>> import myMathFun >>> def main(): ... print '1+2+...5= %d'%myMathFun.sumHierarchy(5) >>> if __name__=='__main__': ... main() ·ín¤Þ¤J¯S©wª«¥óÃþ§O©Î¨ç¦¡®É¡G >>> # main.py >>> from myMathFun import sumHierarchy >>> def main(): ... print '1+2+...5= %d'%sumHierarchy(5) >>> if __name__=='__main__': ... main() °õ¦æµ²ªG¬°¡G python main.py 1+2+...5= 15
  • 22. ¦b¤Wz¨Ò¤l¤¤ __name__ ±`¼Æ¬O¨C¤@Ó¼Ò²Õ³£¦³ªº¤º«Ø±`¼Æ¡A³oÓ±`¼ÆªºÈ ´N¬O¼Ò²Õªº¦WºÙ(¤]¬OÀɮתº¦WºÙ)¡A·ípythonª½Ä¶¾¹¦b°õ¦æ¤@ÓpythonÀɮ׮ɡA¥¦·| ±N¦¹±`¼Æ__name__ªºÈ§ï¦¨__main__¤]´N¬O¤Á¤Jµ{¦¡°õ¦æªºÂI¡A©Ò¥H¦b¦¹ if §PÂ_¦¡¤ ¤©Ò°õ¦æªº¨ç¦¡©Îµ{¦¡´N·|¦bµ{¦¡¤@¶}©l°õ¦æ®É³Q¸ü¤J¹B§@¡C python ®M¥ó³B²z ¦bpython¤¤¡A§A¥i¥H±N¦hÓ¦PÃþ«¬©ÎÄݩʪº¼Ò²Õ¶°¤¤¦b¦P¤@ӥؿý¤¤¡A¨Ã¦b¥Ø¿ý¤¤¥[¤J __init__.pyªºÀɮסA¨Ó²Õ¦X¦¨¤@Ó®M¥ó¡C °²³]¦³Ó®M¥óªº¥Ø¿ý¦¨ûµ²ºc¦p¤U¡G mylib/ __init__.py myMathFun.py countNum.py Yn¤Þ¤JmyMathFun¼Ò²Õ¡A¥i¥H¦bÀɮפW¤è¥[¤J >>> from mylib import myMathFun Yn¨Ï¥ÎmyMathFun¤¤ªºÃþ§Oª«¥ó©Î¨ç¦¡¡A¥i¥Î >>> #main.py >>> from mylib import myMathFun ..... ..... >>> myMathFun.sumHierarchy(5) ¦b __init__.py¤¤©Ò©w¸qªºª«¥óÃþ§O©Î¨ç¦¡¡A¥iª½±µ¤Þ¤J¨Ï¥Î¡C >>> #mylib/__init__,py >>> def sayHello(): ... print ("hello') >>> #main.py >>> from mylib import sayHello ..... ..... >>> sayHello() ¸ü¤J¼Ò²Õ ½d¨Ò1¡G¸ü¤J¼Ò²Õ >>> import random # ¸ü¤Jrandom¼Ò²Õ >>> print(random.randint(2,29)) # ¨Ï¥Î¨ä¤¤ªºrandint¨ç¦¡ >>> from random import randinr # ¸ü¤Jrandomªºrandint¼Ò²Õ >>> print(randint(2,29)) # ¨Ï¥Î®É¤£¥Î¼g¤@¤j¦ê ½d¨Ò2¡GŪ²Õºô¶ >>> from urllib.request import urlopen # ¸ü¤JŪ¨úºô¶¼Ò²Õ >>> data = urlopen("http://www.cs.pu.edu.tw/~ylyang/vcs_git.html").read() >>> str = data.decode() # Âনutf-8®æ¦¡ >>> print (str) python ¤pµ{¦¡»s§@½d¨Ò ¸Õ§Q¥Î¼Ò²Õ³]p¤@Ó¥i¥H¿ï¾Ü¤GºØ¹Bºâªºpythonµ{¦¡ (1)¥i¥H¿é¤J¤GÓ¾ã¼Æ¥|«h¹Bºâªº¹Bºâ¾¹ (2)¥i¥H¿é¤J¤@Ó¾ã¼ÆÈ,¨Ãpºâ¥¦ªº¶¥¼h¼¿n (3)Â÷¶}
  • 23. ¸Ñµª: # homework.py # coding: utf-8 import re,math def isValidFormula(strFormula): regexp =re.compile(r'd{1,5}[+|-|*|/]d{1,5}') if regexp.search(strFormula): return True return False def getArithmeticResult(strFormula): try: if isValidFormula(strFormula): return eval(strFormula) else: return 'input error' except: return 'input error' def getFactorialResult(strNum): if strNum.isdigit(): return math.factorial(int(strNum)) else: return 'input error' def main(): while True: print u''' ½Ð¿ï¾Ü (1)¥i¥H¿é¤J¤GÓ¾ã¼Æ¥|«h¹Bºâªº¹Bºâ¾¹ (2)¥i¥H¿é¤J¤@Ó¾ã¼ÆÈ,¨Ãpºâ¥¦ªº¶¥¼h¼¿n (3)Â÷¶} ''' strChoice=raw_input('Select:') if strChoice.strip()=='1': print u'½Ð¿é¤J¹Bºâ¦¡:' strFormula=raw_input() print u'%s=%s'%(strFormula,getArithmeticResult(strFormula)) elif strChoice.strip()=='2': print u'½Ð¿é¤J¶¥¼h¼Æ¦r:' strNum=raw_input() print u'%s!=%s'%(strNum,getFactorialResult(strNum)) elif strChoice.strip()=='3': break else: print 'your choice is error' print '==========================================' if __name__=='__main__': main()