python學習手冊教程 課程實驗_第1頁
python學習手冊教程 課程實驗_第2頁
python學習手冊教程 課程實驗_第3頁
python學習手冊教程 課程實驗_第4頁
python學習手冊教程 課程實驗_第5頁
已閱讀5頁,還剩150頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1.打開開發(fā)工具PythonIDLE

2.在IDLE中編碼執(zhí)行下列代碼數(shù)字類型例子

>>>importmath

>>>math.pi

3.1415926535897931

>>>math.sqrt(121)

11.0

>>>importrandom

>>>random.random()

0.1976304621238707

>>>random.choice([l,315,7,ll,13]);

3

3.繼續(xù)在IDLE中編寫關(guān)于字符串類型操作例子

>>>s="spam"

>>>len(s)

4

4.繼續(xù)在IDLE中編寫關(guān)于字符串索引操作例子

>>>s="spam"

>>>s[l]

P

?>s[-l]

'm'

5.繼續(xù)在IDLE中編寫關(guān)于字符串索引分片提取操作例子

>>>s="spam”

>>>s[l:3]

'pa'

>>>

6.繼續(xù)在IDLE中編寫關(guān)于字符串變量重新賦值操作例子

>>>s

'spam'

>>>s='z'+s[l:]

>>>s

'zpam"

7.繼續(xù)在IDLE中編寫關(guān)于尋求幫助的操作例子

>>>help(s.lower)

Helponbuilt-infunctionlower:

lower(...)

S.lower()->string

ReturnacopyofthestringSconvertedtolowercase.

>>>

8.繼續(xù)在IDLE中編寫關(guān)于字符串匹配模式的例子

>>>importre

>>>match=re.match('Hello[\t]*(*)world','HelloPythonworld')

>>>match.group(l)

Python,

>>>

>>>match=re.match(7(.*)/(.*)/(.^'.'/usr/home/luberjack')

>>>match.groups()

('usr','home','luberjack')

9繼續(xù)在IDLE中編寫列表操作例子

?>L=[123,'spam',1.12]

>>>len(L)

3

?>L[0]

123

?>L[:-l]

[123,'spam']

?>L+[4,5,6]

[123,'spam;1.1200000000000001,4,5,6]

?>L

[123,'spam',1.1200000000000001]

?>L

[123,'spam1,1.1200000000000001]

>>>L.append('NI')

>>>L

[123,'spam;1.1200000000000001,'Nl']

>>>L.pop⑵

1.1200000000000001

?>L

[123,'spam','Nl']

?>M=[,bb','aa',,cc,]

>>>M.sort()

>>>M

['aa\'bb'.'cc']

>>>M.reverse()

>>>M

fee',,bb'?'aa']

?>L

[123,'spam','Nl']

?>L[99]

Traceback(mostrecentcalllast):

File,,<pyshell#84>",line1,in<module>

L[99]

IndexError:listindexoutofrange

?>L[99]=l

Traceback(mostrecentcalllast):

File"<pyshell#85>",line1,in<module>

L[99]=l

IndexError:listassignmentindexoutofrange

>>>

?>M=[[l,2,3]1[415,6]t[7,8,9]]

>>>M

[[1,2,3],[4,5,6],[7,8,9]]

>>>M[l]

[4,5,6]

>>>M[l][l]

5

>>>M

[[1,2,3],[4,5,6],[7,8,9]]

>>>cols=[row[l]forrowinM]

>>>cols

[2,5,8]

>>>[row[l]+lforrowinM]

[3,6,9]

>>>[row[l]forrowinMifrow[l]%2==0]

[2,8]

?>diag=[M[i][i]foriin[0,1,2]]

>>>diag

[1,5,9]

>>>doubles=[c*2forcin'spam']

>>>doubles

['ss','pp",'aa','mm']

>>>

4.打開開發(fā)工具PythonIDLE

5.在IDLE中編寫運行關(guān)于字典創(chuàng)建和使用的例子

>>>D={,food,:,spam,,,quantity,:4,,color,:,pink'}

>>>D

{'food':'spam','color':'pink','quantity':4}

?>D['food']

"spam'

>>>D=CfoodYspam'/quantity'^/color'/pink')

>>>D['quantity']+=1

>>>D['quantity']

5

>>>D

{'food':'spam','color':'pink','quantity':5}

>>>D=0

>>>D「name']二'Bob'

>>>D['age']=40

>>>D

{"age':40,'name':'Bob'}

6.繼續(xù)在IDLE中編寫關(guān)于創(chuàng)建和使用嵌套字典的例子

,,,,,,,

>>>rec={name':{first':Bobt'last':'Smith}1'job':['dev','mgr]/age:40.5}

>>>rec

{'age':40.5,"job':['dev','mgr'],'name':{'last':'Smith','first':'Bob'}}

>>>rec['name']

{'last':'Smith','first':'Bob')

>>>recf'namejnast']

,Smith'

>>>rec['job1][-l]

'mgr'

>>>recHob^appendCjanitor')

>>>rec

{'age':40.5,"job':['dev','mgr','janitor'],'name':{'last':'Smith','first':'Bob'}}

4.繼續(xù)在IDLE中編寫關(guān)于使用for循環(huán)對字典進行排序的例子

?>D={'a':L'b':2,'c':3}

>>>D

{'a':1,'c':3,'b':2}

>>>Ks=D.keys()

>>>Ks

⑻七/b]

>>>Ks.sort()

>>>Ks

['a\'b;'c']

>>>forkeyinKs:

printkey,'=>>,D[key]

a=>1

b二>2

c二>3

>>>D

{'a':1,'c':3,'b':2}

>>>forkeyinsorted(D):

printkey,'=>',D[key]

a=>1

b=>2

c=>3

5,繼續(xù)在IDLE中編寫關(guān)于使用for循環(huán)操作字符串例子

>>>forcin'spam':

printc.upperQ

S

P

A

M

6,繼續(xù)在IDLE中編寫關(guān)于迭代和優(yōu)化例子

>>>squares=[x**2forxin[l,2,3,4,5]]

>>>squares

[1,4,9,16,25]

>>>squares二口

>>>forxin[1,2,3,4,5]:

squares.append(x**2)

>>>squares

[1,4,9,16,25]

7.繼續(xù)在IDLE中編寫關(guān)于字典不存在的鍵的測試操作例子

>>>D

{'a':1.'c':3,'b':2}

?>D[,e']=99

>>>D

{'a':1,'c':3,'b':2,'e':99}

>>>

Traceback(mostrecentcalllast):

File"<pyshell#39>",line1,in<module>

D[,f1]

KeyError:'f'

>>>D.has_key('f)

False

>>>ifnotD.has_key('f"):

print字典D中不包含鍵為f的值’

字典D中不包含鍵為f的值

8,繼續(xù)在IDLE中編寫關(guān)于元組創(chuàng)建和使用的例子

?>T=(L234)

>>>len(T)

4

?>T+(4,5)

(1,2,3,4,4,5)

?>T[0]

1

?>T[0]=2

Traceback(mostrecentcalllast):

File"<pyshell#48>",line1,in<module>

T⑼二2

TypeError:'tuple'objectdoesnotsupportitemassignment

>>>

7.打開開發(fā)工具PythonIDLE

8.在IDLE中編寫運行關(guān)于文件操作的例子

>>>f=open('data.txt',,w,)

>>>f.write('hello\n')

>>>f.write('world\n')

>>>f.close()

>>>f=open('data.txt')

?>f

<openfile'data.txt',modeTat0x011D6910>

>>>bytes=f.read()

>>>bytes

,hello\nworld\n'

>>>printbytes

hello

world

>>>bytes.split()

['hello','world']

在安裝Python默認路徑下會產(chǎn)生一個data.txt的文件,

9.繼續(xù)在IDLE中編寫關(guān)于創(chuàng)建和使用集合的例子

>>>X=set('spam')

?>Y=set(['h,,,a','m1])

?>X,Y

(set(['a','p','s','m']),set(['a','h',,m']))

?>X&Y#交運算

set(['a',,m'])

?>X|Y#并運算

set(['a','p','s','h',,m'])

?>X-Y#差運算

set(['p','s'])

4,繼續(xù)在IDLE中編寫關(guān)于使用Decimal小數(shù)對象的例子

>>>0.1

0.10000000000000001

>>>0.1+1

1.1000000000000001

>>>importdecimal

>>>d=decimal.Decimal('O.l')

>>>d+1

Decimal('l.l')

5.繼續(xù)在IDLE中編寫關(guān)于使用布爾類型對象例子

>>>1>2,1<2

(False,True)

>>>bool('spam')

True

6.繼續(xù)在IDLE中編寫關(guān)于None類型例子

>>>X=None

>>>printX

None

>>>L=[None]*5

>>>L

[None,None,None,None,None]

>>>type(L)

<type'list'〉

?>type(type(L))

<type'type'〉

7.繼續(xù)在IDLE中編寫關(guān)于對象類型檢查測試的例子

>>>L

[None,None,None,None,None]

>>>iftype(L)==type([]):

print"yes"

yes

>>>iftype(L)==list:

print'yes'

yes

>>>ifisinstance(LJist):

print'yes'

yes

8.繼續(xù)在IDLE中編寫關(guān)于類創(chuàng)建和類的實例創(chuàng)建的例子

>>>classWorker:

def_init_(self,name,pay):

=name

self.pay=pay

deflastName(self):

return.split()[-l]

defgiveRaise(self,percent):

self.pay*=(1.0+percent)

?>bob=Worker('BobSmith,,50000)

>>>sue=Worker('sueJones,,60000)

>>>bob.lastNameQ

,Smith'

>>>sue.lastName()

'Jones'

>>>sue.giveRaise(.lO)

>>>sue.pay

66000.0

10.打開開發(fā)工具PythonIDLE

11.在IDLE中編寫運行關(guān)于數(shù)字變量和基本表達式的例子

>>>a=3

>>>b=4

>>>a+l,a-l

(4,2)

>>>b*3,b/2

(12.2)

>>>a%2,b**2

(L16)

>>>2+4,0,2.0**b

(6.0,16.0)

>>>b/2+a

5

>>>printb/(2.0+a)

0.8

>>>c*2

Traceback(mostrecentcalllast):

File"<pyshell#8>",line1,in<module>

c*2

NameError:name'c'isnotdefined

12.繼續(xù)在IDLE中編寫關(guān)于數(shù)字顯示格式的例子

>>>b,a

(4,3)

?>b/(2.0+a)

0.80000000000000004

?>1/2,0

0.5

>>>printb/(2.0+a)

0.8

>>>num=l/3.0

>>>num

0.33333333333333331

>>>printnum

0.333333333333

>>>'%e*%num

,3.3333336-01,

>>>,%2.2f%num

'0.33'

>>>repr(num)

,0.33333333333333331,

>>>str(num)

,0.333333333333,

4.繼續(xù)在IDLE中編寫關(guān)于傳統(tǒng)除法、Floor除法和真除法的例子

>>>(5/2),(5/2.0),(5/-2.0),(5/-2)

(2,2.5,-2.5,-3)

?>(5//2),(5//2.0),(5//-2.0),(5//-2)

(2,2.0,-3.0,-3)

?>(9/3),(9.0/3),(9//3),(9//3.0)

(3,3.0,3,3.0)

>>>from_future_importdivision

?>(5/2),(5/2.0),(5/-2.0),(5/-2)

(2.5,2.5,-2.5,-2.5)

?>(5//2),(5//2.0),(5//-2.0),(5//-2)

(2,2.0,-3.0,-3)

?>(9/3),(9,0/3),(9//3),(9//3.0)

(3.0,3.0,3,3.0)

>>>

5.繼續(xù)在IDLE中編寫關(guān)于位操作例子

?>x=l#00000001

?>x?2#00000100

4

?>x|2#00000011

3

?>x&3#00000001

1

6.繼續(xù)在IDLE中編寫關(guān)于長整型數(shù)字例子

?>99999999999999999999999999999999+1

100000000000000000000000000000000L

>>>2L**200

1606938044258990275541962092341162602522202993782792835301376L

>>>2**200

1606938044258990275541962092341162602522202993782792835301376L

7,繼續(xù)在IDLE中編寫關(guān)于復數(shù)例子

?>lj*lJ

(-l+0j)

>>>2+lj*3

(2+3j)

?>(2+lj)*3

(6+3j)

8.繼續(xù)在IDLE中編寫關(guān)于十六進制和八進制記數(shù)的例子

>>>01,010,0100

(1,8,64)

>>>0x01,0x10,Oxff

(1,16,255)

>>>oct(64),hex(64),hex(255)

('0100','0x40','Oxff')

1,,1,

?>intC0100),int(010058),int(0x40,16)

(100,64,64)

?>eval('100)eval('0100)eva(0x40')

(100,64,64)

?>"%o%x%X"%(64,64,255)

,10040FF'

9.繼續(xù)在IDLE中編寫關(guān)于其他內(nèi)置數(shù)學工具的例子

>>>math.pi,math.e

(3.1415926535897931,2.7182818284590451)

>>>math.sin(2*math.pi/180)

0.034899496702500969

>>>math.sqrt(144),math.sqrt(2)

(12.0,1.4142135623730951)

>>>abs(-42),2**4,pow(2,4)

(42,16,16)

>>>int(2.567),round(2.567),round(2.567,2)

(2,3.0,2,5699999999999998)

>>>importrandom

>>>random.random()

0.031193863487957163

>>>random.randint(l,10)

2

>>>random.randint(l,10)

10

>>>random.randint(l,10)

7>>>random.choice([,aaa',,bbb',,ccc,,,ddd,])

'bbb'

,,,,,,,

>>>random.choice([aaa1bbb,'ccc,ddd])

'ccc'

10.繼續(xù)在IDLE中編寫關(guān)于小數(shù)數(shù)字的例子

>>>0.1+0.1+0.1

0.30000000000000004

>>>print0.1+0.1+0.1-0.3

5.55111512313e-17

>>>fromdecimalimportDecimal

?>Decimal('0.:L')+Decimal('0.r)+Decimal('0.1')-Decimal('0.3')

Decimal('O.O')

?>Decimal(Qr)+Decimal(Q10')+Decimal(Q10')-Decimal(Q30')

DecimalCO.OO')

>>>Decimal('l')/Decimal('7')

DecimalCO.1428571428571428571428571429')

11.繼續(xù)在IDLE中編寫關(guān)于集合的例子

>>>x=set('abcde')

>>>y=set('bdxyz')

>>>x

set(['a'.'c\'b;'e;|d'])

>>>'e'inx

True

>>>x-y

set(['a','c',,e'])

>>>x|y

set(['a','c','b','e;'d',y,'x;'z'])

>>>x&y

set(['b\'d'])

>>>engineers=set([,bob',,sue',,ann,,'vic'])

>>>managers=set([tom','sue'])

>>>engineers&managers

set(['sue'])

>>>engineers|managers

se^f'vic','sue','tom','bob','ann'])

>>>engineers-managers

set(['vic','bob','ann'])

13.打開開發(fā)工具PythonIDLE

14.在IDLE中編寫運行關(guān)于變量聲明賦值類型的例子

>>>a=3

>>>a='spam'

>>>a=1,23

>>>a+=l

>>>a

15.繼續(xù)在IDLE中編寫關(guān)于共享引用和修改查看的例子

?>Ll=[2,3.4]

?>L2=L1

?>Ll[0]=24

?>LI

[24,3,4]

?>L2

[24,3,4]

?>Ll=[2,3,4]

?>L2=L1[:]

?>Ll[0]=24

?>LI

[24,3,4]

?>L2

[2,3,4]

>>>importcopy

?>Y=[l,2,3]

>>>X=copy.copy(Y)

?>X

[1,2,3]

>>>C=copy.deepcopy(Y)

>>>C

[1,2,3]

4.繼續(xù)在IDLE中編寫關(guān)于變量測試相等的例子

?>L=[l,2,3]

>>>M=L

>>>L==M

True

>>>LisM

True

?>L=[123]

?>M項23]

>>>L==M

True

>>>LisM

False

?>X=42

?>Y=42

?>X==Y

True

?>XisY

True

>>>importsys

>>>sys.getrefcount(42)

8

16.打開開發(fā)工具PythonIDLE

17.在IDLE中編寫運行關(guān)于字符串常量的例子

>>>'shrubbery1,"shrubbery"

('shrubbery','shrubbery')

?>'knight's',"knight's"

('knight's',"knight's")

>>>title="Meangin"'of"Life"

>>>title

*MeanginofLife'

>>>'knightVs'/'knightVs"

("knight's",'knighf's')

>>>s='a\nb\tc'

>>>s

'a\nb\tc'

>>>prints

a

bc

>>>len(s)

5

>>>s='a\0b\0c'

>>>s

'a\x00b\x00c1

>>>len(s)

5

>>>x="c:\py\code"

>>>x

'c:\\py\\code'

>>>len(x)

10

18.繼續(xù)在IDLE中編寫關(guān)于Row字符串的例子

>>>myfile=open(r'C:\new\text.dat','w,)

>>>path=「'C:\new\text.dat'

>>>path

'C:\\new\\text.dat'

>>>printpath

C:\new\text.dat

>>>len(path)

15

4,繼續(xù)在IDLE中編寫關(guān)于三重引號的塊字符串常量的例子

>>>matra=Alwayslook

...onthebrighr

...sideoflife."""

>>>matra

'Alwayslook\n...onthebrighr\n...sideoflife.,

>>>

5.繼續(xù)在IDLE中編寫關(guān)于Unicode字符串常量的例子

>>>u'spam'

u'spam"

>>>'ni'+u'spam'

u'nispam'

>>>str(u'spam')

"spam'

>>>unicode('spam')

u'spam'

>>>

6,繼續(xù)在IDLE中編寫關(guān)于實際應(yīng)用中的字符串的例子

>>>len('abc')

3

>>>'abc'+'def'

'abcdef'

?>'Ni!'*4

'Ni!Ni!Ni!Ni!'

>>>print'_'*30

>>>myjob="hacker”

>>>forcinmyjob:printc

h

a

c

k

e

r

>>>

>>>"k"inmyjob

True

>>>'z'inmyjob

False

7,繼續(xù)在IDLE中編寫關(guān)于字符串索引和分片的例子

>>>s='abcdefghijklmnop'

?>s[l:10:2]

,bdfhj,

>>>s|j:2]

'acegikmo'

>>>s[::-2]

,pnljhfdb'

>>>s='hello'

>>>s[::-l]

,olleh,

>>>s='abcedfg'

>>>s[5:l:-l]

'fdec'

8.繼續(xù)在IDLE中編寫關(guān)于字符串轉(zhuǎn)換工具的例子

?>int('42'),str(42)

(42,'42)

?>repr(42)/42,

('42','42')

>>>'42'

'42'

?>repr(42);42'

('42',,421)

>>>s="42"

>>>i=l

>>>s+i

Traceback(mostrecentcalllast):

File"<pyshell#63>",line1,in<module>

s+i

TypeErro匚cannotconcatenate'str'and'int'objects

>>>int(s)+i

43

>>>s+str(i)

'421'

?>str(2.1415),float('1.5')

(12.14151,1.5)

?>text='1.234E-10'

>>>float(text)

1.2340000000000001e-10

?>str(2.1415),float('1.5')

(12.14151,1.5)

?>text='1.234E-10'

>>>float(text)

1.2340000000000001e-10

>>>s='5'

>>>s=chr(ord(s)+l)

>>>s

'61

>>>B='1101

>>>1=0

>>>whileB:

l=l*2+(ord(B[0])-ord('0'))

B=B[1:]

?>I

13

9.繼續(xù)在IDLE中編寫關(guān)于修改字符串的例子

>>>S='spam'

?>S[0]='s'

Traceback(mostrecentcalllast):

File"<pyshell#l>",line1,in<module>

S[0]='s,

TypeError:'str'objectdoesnotsupportitemassignment

?>S=S+,'SPAM!"

>>>s

,spamSPAM!,

?>S=S[:4]+'Burger'+S[-l]

>>>S

'spamBurger!'

>>>S='splot'

>>>S=S.replaceCpI'/pamal')

>>>S

'spamalot,

10.繼續(xù)在IDLE中編寫關(guān)于字符串格式化的例子

>>>exclamation="Ni"

>>>"Theknightswhosay%s!"%exclamation

TheknightswhosayNi!'

?>"%d%s%dyou"%(l/spam',4)

'1spam4you'

?>"%s--%s--%s"%(42,3.14159,[1,2,3])

,42--3.14159--[1,2,3],

>>>x=1234

>>>res="integers:...%d...%-6d...%06d"%(x,x,x)

>>>res

,integers:...1234...1234...001234,

?>x=1.23456789

>>>x

1.2345678899999999

?>,%e|%f|%g1%(x,x,x)

11.2345686+00|1.234568|1.23457,

>>>

?>,%-6.2f|%05,2f|%+Of.lf%(x,x,x)

11.繼續(xù)在IDLE中編寫關(guān)于字符串方法的例子

>>>s='spammy'

>>>s=s.replace('mm','xx,)

>>>s

'spaxxy'

?>"aa$bb$cc$dd".replace(,,$",,SPAM,)

,aaSPAMbbSPAMccSPAMdd,

>>>s='xxxSPAMxxxxSPAMxxxx'

?>s.replace(,SPAM,/EGGS,)

'xxxEGGSxxxxEGGSxxxx'

?>s.replaceCSPAM'/EGGS'.l)

,xxxEGGSxxxxSPAMxxxx'

>>>s='xxxxSPAMxxxxSPAMxxxx'

>>>where=s.find('SPAM')

>>>where

4

>>>s=s[:where]+'EGGS'+s[(where+4):]

>>>s

,xxxxEGGSxxxxSPAMxxxx'

>>>s='spammy'

>>>L=list⑸

?>L

[?s','p\*a','m','m',y]

?>L[3]='x"

?>L[4]='x'

?>L

['s','p;'a\'x;Y,y]

>>>s="".join(L)

>>>s

'spaxxy'

,",,,,,

>>>SPAM'.join(['eggs,sausage'1ham1toast])

,eggsSPAMsausageSPAMhamSPAMtoast'

12.繼續(xù)在IDLE中編寫關(guān)于文本解析的例子

>>>line='aaabbbccc'

>>>coll=line[0:3]

>>>col3=line[8:]

>>>coll

'aaa'

>>>col3

'ccc'

>>>cols=line.split()

>>>cols

['aaa','bbb','ccc']

>>>line='bob,hacker,40'

>>>line.split(',')

['bob','hacker;'40']

?>line="i'mSPAMaSPAMLUMBERJACK"

>>>line.splitCSPAM')

["i'm",'a','LUMBERJACK']

13.繼續(xù)在IDLE中編寫關(guān)于字符串其它方法的例子

>>>line="TheknightswhosyNi!\n"

>>>line.rstrip()

,TheknightswhosyNi!,

>>>line.upper()#轉(zhuǎn)大寫

,THEKNIGHTSWHOSYNl!\n'

>>>line.isalpha()

False

>>>line.endswith('Ni!\n')

True

?>line.find('Ni')!=-l

True

>>>'Ni'inline

True

?>sub="Ni!\n"

>>>line.endswith(sub)

True

>>>line[-len(sub):]==sub

True

19.打開開發(fā)工具PythonIDLE

20.在IDLE中編寫運行關(guān)于基本列表操作的例子

?>len([l,2,3])

3

?>[1,2,3]+[4,5,6]

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

?>['Ni!']*4

[Ni!','Ni!「Ni!丁Ni![

?>3in[1,2,3]

True

>>>forxin[l,2f3]:printx

1

2

3

?>str([l,2])+"34"

IL2]34,

?>[l,2]+listC,34")

[1,2,3,4]

21.繼續(xù)在IDLE中編寫關(guān)于列表索引、分片和矩陣的例子

?>L=['spam,;Spam';,SPAM!"]

?>L[2]

'SPAM!'

>>>L[-2]

Spam'

?>L[l:]

['Spam','SPAM!']

>>>matrix=[[l,2,3],[4,5,6],[7,8,9]]

>>>matrix[l]

[4,5,6]

>>>matrix[l][l]

5

>>>matrix[2][0]

7

4,繼續(xù)在IDLE中編寫關(guān)于列表方法調(diào)用的例子

?>L=['spam,:Spam,;'SPAM!"]

>>>L[l]='eggs'

?>L

['spam','eggs;'SPAM!']

>>>L[0:2]=['eat','more']

?>L

['eat,'more','SPAM!']

>>>L.append('please')

>>>L

['eat;'more;'SPAM!','please']

>>>L.sort()

>>>L

['SPAM!",'eat;'more;'please']

>>>L.extend(['aaa",,bbb'])

?>L

['SPAM!','eat','more','please','aaa','bbb']

?>L.pop()

'bbb'

?>L

['SPAM!','eat','more','please','aaa']

>>>L.reverse()

?>L

['aaa\'please;'more','eat','SPAM!']

5.繼續(xù)在IDLE中編寫關(guān)于原處修改列表的常見操作的例子

?>L

['aaa','please','more','eat','SPAM!']

>>>delL[0]

?>L

['please','more','eat','SPAM!']

>>>delL[l:]

?>L

['please*]

>>>L=["Already",'got','one']

?>L[1:]=D

?>L

['Already']

>>>L[O]=D

?>L

[0]

>>>

22.打開開發(fā)工具PythonIDLE

23.在IDLE中編寫運行關(guān)于字典基本操作的例子

>>>d2={,spam1:2,"ham':l,'eggs,:3}

>>>d2['spam']

2

?>d2

{"eggs':3,'ham':1,'spam':2}

>>>Ien(d2)

3

>>>d2.has_key('ham')

True

>>>'ham*ind2

True

>>>d2.keys()

['eggs','ham','spam']

24.繼續(xù)在IDLE中編寫關(guān)于修改原處字典的例子

>>>d2[,ham,]=[,grill','bake','fry']

?>d2

{'eggs':3,"ham':['grill1,'bake',"fry'],'spam':2)

>>>deld2['eggs']

?>d2

{'ham':['grill','bake",'fry'],'spam':2}

>>>d2[,brunch']="Bacon,

?>d2

{'brunch':'Bacon','ham':['grill','bake','fry1],'spam':2}

4,繼續(xù)在IDLE中編寫關(guān)于字典的方法的例子

>>>d2={'spam':2,'ham':l,'eggs':3}

>>>d2.values()

[3,1,2]

>>>d2.items()

[('eggs',3),('ham1,1).('spam',2)]

>>>d2.get('spam')

2

>>>d2.get('toast')

>>>d2.get('toast,,88)

88

?>d2

{'eggs':3,'ham':1,'spam':2}

>>>d3={,toast':4,,muffin':5}

>>>d2.update(d3)

?>d2

{1toast':4,'muffin':5,'eggs':3,'ham':1,'spam':2)

>>>d2.pop('muffin')

5

>>>d2.pop('toast')

4

?>d2

{'eggs':3,'ham':1,'spam':2}

>>>

5,繼續(xù)在IDLE中編寫例子語言表

>>>table={'Python':'GuidovanRossum'/Perl'/LarryWall'/Tcl'/JohnOusterhout')

>>>language='Python'

>>>creator=table[language]

>>>creator

'GuidovanRossum'

>>>forlangintable.keys():

printlang/Xt'.tableflang]

PythonGuidovanRossum

TelJohnOusterhout

PerlLarryWall

>>>

6,繼續(xù)在IDLE中編寫關(guān)于字典用法的相關(guān)例子

>>>matrix二{}

>>>matrix[(2,3,4)]=88

>>>matrix[(7,819)]=99

>>>x=2;y=3;z=4

>>>matrix[(x,y,z)]

88

>>>matrix

{(2,3,4):88,(7,8,9):99}

>>>ifmatrix.has_key((2,3,6)):

printmatrix[(2,3,6)]

else:

print0

0

>>>try:

printmatrix[(2,3,6)]

exceptKeyError:

print0

0

>>>matrix.get((2,3,6),0)

0

>>>rec=§

>>>recf'name^'mel'

>>>rec['age']=45

>>>rec['job*]='trainer/writer'

>>>rec['name']

,mel,

>>>dl={'name':'mel','age':45}

>>>d2={}

>>>d2]name[='mel'

>>>d2[,age1]=45

>>>d3=dict(name='mer,age=45)

,,,

>>>d4=dict([('name1mer),('age,45)])

>>>d4

{'age':45,'name':'mel'}

>>>d3

{'age':45,'name':'mel'}

25.打開開發(fā)工具PythonIDLE

26.在IDLE中編寫運行關(guān)于元組基本操作的例子

>?(1.2)+(3.4)

(1,2,3,4)

?>(1,2)*4

(1,2,1,2,1,2,1,2)

>?T=(1,2,3,4)

?>T[0],T[l:3]

(1.(2,3))

>>>x=(40)

>>>x

40

?>y=(40,)

>>>y

(40,)

27.繼續(xù)在IDLE中編寫關(guān)于元組的改變的例子

?>T=('cc,;aa,,,dd,,,bb,)

>>>tmp=list(T)

>>>tmp.sort()

>>>tmp

['aa\'bb','cc;'dd']

>>>T=tuple(tmp)

?>T

('aa\'bb','cc;'dd')

>?T=(1,2,3,4I5)

>>>L=[x+20forxinT]

?>L

[21,22,23,24,25]

?>T=(l,[2,3],4)

>>>T[l]='spam"

Traceback(mostrecentcalllast):

File"<pyshell#59>",line1,in<module>

T[l]='spam'

TypeError:'tuple'objectdoesnotsupportitemassignment

>>>T[l][0]='spam'

?>T

(1,['spam',3],4)

28.打開開發(fā)工具PythonIDLE

29.在IDLE中編寫運行關(guān)于文件的基本操作的例子

>>>myfile=open('myfile','w')

>>>myfile.write('hellotextfile\n')

>>>myfile.close()

>>>myfile=open('myfile')

>>>myfile.readline();

'hellotextfile\n'

>>>myfile.readline()

30.繼續(xù)在IDLE中編寫關(guān)于在文件中存儲并解析Python對象的例子

>>>x,y,z=43,44,45

>>>s='spam'

?>D={'a':L'b':2}

?>L=[l,2,3]

'

>>>F=open('datafile.txt'I'w)

>>>F.write(s+'\n')

>>>F.write('%s,%s,%s\n'%(x,y,z))

?>F.write(str(L)+'$'+str(D)+'\n')

>>>F.close()

>>>bytes=open('datafile.txt').read()

>>>bytes

"spam\n43,44,45\n[l,2,3]${'a':1,'b':2}\n"

>>>printbytes

spam

43,44,45

[1,2,3]${'a,:2}

>>>F=open('datafile.txt')

>>>line=F.readline()

>>>line

'spam\n'

>>>line.rstrip()

'spam"

>>>line=F.readline()

>>>line

'43,44,45\n'

>>>parts=line.split(',')

>>>parts

['43',,44','45\n']

>>>int(parts[l])

44

>>>numbers=[int(P)forPinparts]

>>>numbers

[43,44,45]

>>>line=F.readline()

>>>line

"[1,2,3]${'a':1,'b':2}\n"

>>>parts二line.split($)

>>>parts

['[1,2,3]',"{'a':1,'b':2}\n"]

>>>eval(parts[O])

[1,2,3]

>>>objects=[eval(p)forpinparts]

>>>objects

[[1,2,3],{'a1:Lb:2}]

4.繼續(xù)在IDLE中編寫關(guān)于儲存Python的原生對象的例子

>>>F=openCdatafile.txt'/w')

>>>importpickle

>>>pickle.dump(D,F)

>>>F.close()

>>>F=open('datafile.txt')

>>>E=pickle.load(F)

?>E

{'a':l,b:2}

>>>open('datafile.txt').read()

”(dpO\nS'a'\npl\nll\nsS'b'\np2\nl2\ns.”

>>>D

{'a':1,'b':2}

>>>

5,繼續(xù)在IDLE中編寫關(guān)于文件中打包二進制數(shù)據(jù)的存儲與解析的例子

>>>F=open('data.bin','wb')

>>>importstruct

',1

>>>bytes=struct.pack(>i4sh'f7,spam,8)

>>>bytes

,\xOO\xOO\xOO\xO7spam\xOO\xO8,

>>>F.write(bytes)

>>>F.close()

>>>F=openCdata.bin'.'rb')

>>>data=F.read()

>>>data

'\x00\x00\x00\x07spam\x00\x08'

>>>values=struct.unpack('>i4sh',data)

>>>values

(7,'spam',8)

31.打開開發(fā)工具PythonIDLE

32.在IDLE中編寫運行關(guān)于對象靈活性的例子

?>L=['abc',[(l,2),([3],4)],5]

?>L[l]

[(1.2),([3],4)]

?>L[l][l]

([3],4)

>?L[l][l][0]

[3]

?>L[l][l][0][0]

3

33.繼續(xù)在IDLE中編寫關(guān)于引用和拷貝的例子

?>L=[l,2,3]

?>D={'a':l,'b':2}

>>>A=L[:]

>>>B=D.copy()

?>A[l]='Ni'

>>>B['c']='spam'

?>L,D

([1,2,3],('a':1,'b1:2})

>>>A,B

([1,'Ni',3],{'a':1,'c':'spam','b':2})

4,繼續(xù)在IDLE中編寫關(guān)于比較、相等性和真值的例子

?>Ll=[l,('a',3)]

?>L2=[l,Ca,,3)]

?>L1==L2,L1isL2

(True,False)

>>>sl='alongerstring'

>>>s2='alongerstring'

>>>sl==s2,sliss2

(True,False)

>>>

5.繼續(xù)在IDLE中編寫關(guān)于內(nèi)置類型陷阱的例子

?>L=[l,2.3]

?>M"L,Y]

>>>M

['x;[1,2,3],Y]

>>>L[l]=0

>>>M

['x,,[1,0,3],,Y']

?>L=[l,2,3]

>>>L[l]=0

?>L

[1,0,3]

>>>M

['x,,[1,2,3],V]

?>L=[4,5,6]

>>>X=L*4

>>>Y=[L]*4

?>X

[4,5,6,4,5,6,4,5,6,4,5,6]

>>>Y

[[4,5,6],[4,5,6],[4,5,6],[4,5,6]]

>>>L[l]=0

?>X

[4,5,6,4,5,6,4,5,6,4,5,6]

>>>Y

[[4,0.6],[4,0,6]t[4,0,6],[4,0,6]]

?>L=['grail']

>>>L.append(L)

>>>L

['grail1,[...]]

?>T=(1,2I3)

?>T(2)=4

SyntaxError:can'tassigntofunctioncall

?>T=T[:2]+(4,)

?>T

(L2.4)

>>>

34.打開開發(fā)工具PythonIDLE

35.在IDLE中編寫運行關(guān)于Python語句的規(guī)則的例子

>>>x=100;y=20

>>>ifx>=100and\

y<50:

print”滿足條件:x>=100andy<5"

print'滿足條件的第二行’

滿足條件:x>=100andy<5

滿足條件的第二行

36.繼續(xù)在IDLE中編寫一個簡單交互式循環(huán)的例子

>>>whileTrue:

reply=raw_input('Entertext:')

ifreply=='stop':break

printreply.upper()

Entertext:text

TEXT

Entertext:abc

ABC

Entertext:system

SYSTEM

Entertext:stop

>>>

4.繼續(xù)在IDLE中編寫對用戶輸入的數(shù)字進行求平方的運算的例子

>>>whileTrue:

reply=raw_input('Enternumber:')

ifreply=='stop':break

printint(reply)**2

Enternumber:10

100

Enternumber:13

169

Enternumbecstop

>>>

5,繼續(xù)在IDLE中編寫用測試輸入數(shù)據(jù)來處理錯誤的例子

>>>whileTrue:

reply=raw_input('Entertext:')

ifreply二二'stop':

break

elifnotreply.isdigitQ:#不是數(shù)字

print'Bad!'*8

else:

printint(reply)**2

Entertext:5

25

Entertext:xyz

Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!

Entertext:11

121

Entertext:stop

>>>

6.繼續(xù)在IDLE中編寫用try語句處理錯誤的例子

>>>whileTrue:

reply=raw_input('Entertext:')

ifreply=='stop,:break

try:

num=int(reply)

except:

print'Bad!'*8

else:#屬于try語句部分(在try中如果沒有異常被檢測到,則執(zhí)行else子句)

printint(reply)**2

Entertext:12

144

Entertext:sss

Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!

Entertext:100

10000

Entertext:stop

>>>

7,繼續(xù)在IDLE中編寫三層嵌套代碼的例子

>>>whileTrue:

reply=raw_input('Entertext:')

ifreply二二'stop’:

break

elifnotreply.isdigit():

print'Bad!"*8

else:

num=int(reply)

ifnum<20:

printlow'

else:

printnum**2

Entertext:aaa

Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!

Entertext:120

14400

Entertext:ll

low

Entertext:19

low

Entertext:20

400

Entertext:stop

>>>

37.打開開發(fā)工具PythonIDLE

38.在IDLE中編寫運行關(guān)于序列賦值語句的例子

>>>nudge=l

>>>wink=2

>>>A,B=nudge,wink

>>>A,B

(1.2)

>>>[C,D]=[nudge,wink]

>>>C,D

(1.2)

>>>nudge,wink=wink,nudge

>>>nudge.wink

(2,1)

?>[abc]=(l,2,3)

>>>a,c

(1.3)

?>(abc)="ABC”

>>>a,c

('A','C')

39.繼續(xù)在IDLE中編寫關(guān)于高級序列賦值語句的例子

>>>string='SPAM'

>>>a,b,c,d=string

>>>a,d

('S\'M')

>>>a,b,c=string

Traceback(mostrecentcalllast):

File"<pyshell#15>",line1,in<module>

a,b,c=string

ValueError:toomanyvaluestounpack

>>>a,b,c=string[0],string[l],string[2:]

>>>a,b,c

(S,P,'AM')

>>>a,b,c=list(string[:2])+[string[2:]]

>>>a,b,c

(S,P,'AM')

>>>a,b=string[:2]

>>>c=string[2:]

>>>a,b,c

('S','P;'AM')

>>>(a,b),c=string[:2],string[2:]

>>>a,b,c

('S','P;'AM')

?>((a,b),c)=(,SP,:AM,)

>>>a,b,c

(S,'P','AM')

>>>red,green,blue=range(3)

>>>red,blue

(0.2)

>>>range(3)

[0,1,2]

?>L=[1,2,3,4]

>>>whileL:

front,L=L[O],L[1:]

printfront,L

1[2,3,4]

2[3,4]

3[4]

4口

4,繼續(xù)在IDLE中編寫關(guān)于多目標賦值語句的例子

>>>a=b二c二'spam'

>>>a,b,c

('spam','spam','spam')

>>>a=b=O

>>>b=b+l

>>>a,b

(0.1)

>>>a二b二口

>>>a.append(42)

>>>a,b

([42],[42])

>>>a二口

>>>b二口

>>>b.append(42)

>>>afb

(□.[42])

5,繼續(xù)在IDLE中編寫關(guān)于增強賦值語句的例子

>>>x=l

>>>x+=l

>>>X

2

>>>s="spam"

?>s+="SRAMH

>>>s

'spamSPAM'

?>L=[l,2]

?>L=L+[3,4]

?>L

[1,2,3,4]

>>>L.append(5)

?>L

[1,2,3,4,5]

?>L+二[6,7,8]

?>L

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

>>>M=L

>>>L+二[9]

>>>M,L

([1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9])

?>L=L+[10]

>>>M,L

([1,2,3,4,5,6,7,8.9],[1,2,3,4,5,6,7,8,9,10])

6,繼續(xù)在IDLE中編寫關(guān)于打印語句的例子

>>>x+a';y='b'

>>>printx,y

ab

>>>printx+y

ab

>>>print'%s...%s,%(x,y)

a...b

>>>importsys

>>>sys.stdout.write('helloworld\n')

helloworld

>>>temp=sys.stdout

>>>sys.stdout=open(,log.txt,,'a')

>>>print'spam'

>>>print1,2,3

>>>sys.stdout.close()

>>>sys.stdout=temp

>>>print'backhere'

backhere

>>>printopen('log.txt').read()

spam

123

>>>log=open('log.txt',W)

>>>print>>log,1,2,3

>>>print>>log,4,5,6

>>>log.close()

>>>printopen('log.txt').read()

123

456

40.打開開發(fā)工具PythonIDLE

41.在IDLE中編寫運行關(guān)于if語句的例子

>>>if1:

print'true'

else:

print'false

true

42.繼續(xù)在IDLE中編寫關(guān)于多路分支語句的例子

>>>x='killerrabbit'

>>>ifx=='roger':

print"how'sjessica?"

elifx二二'bugs’:

print"what'supdoc?"

else:

print'Runaway!Runaway!'

Runaway!Runaway!

>>>branch={'spam':1.25,'ham':1.99,,eggs,:0.99}

>>>printbranch.getCspam'/Badchoice')

1.25

>>>printbranch.getCbacon'.'Badchoice')

Badchoice

4,繼續(xù)在IDLE中編寫關(guān)于語法規(guī)則的例子

>>>ifx:

y=2;

ify:

print'block2'

print'blockl'

block2

Blockl

?>L=["Good",

"Bad",

"Ugly"]

>>>if(a==bandc==dand

d二二eande=二f):

print'olde'

>>>ifa==bandc==dand\

d==eandf==g:

print'olde'

>>>S="""Alwayslook

onthebright

sideoflife......

>>>x=l;y=2;printx

1

>>>ifl:print'hello'

hello

5,繼續(xù)在IDLE中編寫關(guān)于真值測試的例子

>>>2<3,3<2

(True,False)

>>>2or3,3or2

(2.3)

>>>[]or3

3

?>□or{}

0

>>>2and3,3and2

(3.2)

>>>口and0

>>>3andQ

6.繼續(xù)在IDLE中編寫關(guān)于三元表達式的例子

?>X=l;Y=2;Z=3;Z=0

>>>ifX:

A二Y

else:

A=Z

>>>A

2

>>>A=YifXelseZ

>>>A

2

>

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論