Python快速入门by Armand.docx

上传人:b****5 文档编号:8490520 上传时间:2023-01-31 格式:DOCX 页数:29 大小:23.51KB
下载 相关 举报
Python快速入门by Armand.docx_第1页
第1页 / 共29页
Python快速入门by Armand.docx_第2页
第2页 / 共29页
Python快速入门by Armand.docx_第3页
第3页 / 共29页
Python快速入门by Armand.docx_第4页
第4页 / 共29页
Python快速入门by Armand.docx_第5页
第5页 / 共29页
点击查看更多>>
下载资源
资源描述

Python快速入门by Armand.docx

《Python快速入门by Armand.docx》由会员分享,可在线阅读,更多相关《Python快速入门by Armand.docx(29页珍藏版)》请在冰豆网上搜索。

Python快速入门by Armand.docx

Python快速入门byArmand

************************************************************************************

INSTRUCTION

Thistipsisanoteafterreadingbooksasfollow:

(secondedition)

Ittakesmeaboutaweektoknowwellstyleofpython-program.C-languageandVB–languagehavebeenmywork-toolbeforethis.pythonissimpleandniceaswellasworth-learning.

*************************************************************************************

Redfortitle___

Lightblueforimportantcode___

Lightgreenforimportantinformation___

Contents

1BasicusageofPython1

2datastructureinPython3

3List-slaveofpython5

4TupleString-unmutable9

5Dictionary--whenindexisnotgood10

6Conditioncycleandotherstatement13

7Abstraction—function18

8MoreAbstract21

9exceptionhandling27

10magicmethod29

11standardlibrary31

12fileoperation32

13GUI37

14Package-about__init__41

*************************************************************************************

1BasicusageofPython

Printx

X=input(“plsinputthevalue:

”)

importmathshouldalwaysusemodulebythisway

math.floor(32.9)

int(math.floor(32.9))

frommathimportsqrt

sqrt(9)

name=raw_input("what'syourname?

:

")

print"hello."+name+"!

"

#hereisexplanatorynote

doublequotationmarksisequaltosingleoneinstringusage.

exp:

print"let'sgo"

print'let\'sto'

print"\"hello,world\"shesaid"

stringsmerge:

"let'sknow""aboutyou"

or

x="hello"

y="everyone"

x+y

>>>"helloworld"

'helloworld'

>>>10000L

10000L

>>>print"helloworld"

helloworld

>>>print10000L

10000

Butsometimesweneedtoknowthedetailsofthevalueprinted.

>>>printrepr("helloworld")

'helloworld'

>>>printrepr(10000L)

10000L

>>>printstr("hello,world")

hello,world

>>>printstr(10000L)

10000

functioninputandraw_input:

name=input("plsinputyourname:

")--youneedtoinput"wangwei"

name=raw_input("plsinputyourname:

")--youneedtoinputwangwei

2datastructureinPython

Mostimportantdatastructureofpythonissequencewhichincludelist

(1)tuple

(2)string(3)andsoon.

listcanbemodifiedandtuplecan'tbemodified.listcanreplacetupleinalmostalltheconditionexceptbeingthekeyofdictionary.

theindexofsequencewillstartfrom0.

Asequencecanbeincludedinanotherone.as:

>>>wang=["wangwei",23]

>>>zhang=["zhangsheng",25]

>>>database=[wang,zhang]

>>>database

Generaloprationsofsequence

1indexing

>>>greeting='hello'

>>>greeting[0]

>>>greeting[-1]

#willbeo

ifafunctionreturnasequence,wecanputindexingoperationonitdirectly.

>>>fourth=raw_input(year:

)[3]

year:

2005

>>>fourth

'5'

2sliceing--accesstoarangeofelements

tag[left,right]

leftisthebeginningindex.

rightistheindexafterthelastelement.

>>>numbers=[1,2,3,4,5,6,7,8,9.10]

>>>numbers[3:

6]

[4,5,6]

>>>numbers[0:

1]

[1]

>>>numbers[-3:

-1]

[8,9]

>>>numbers[-3:

]

[8,9,10]

>>>numbers[:

3]

[1,2,3]

>>>numbers[:

]

willprintallmembers

3adding---meansmerging

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

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

>>>'hello'+'world'

'helloworld'

4multiply--meansrepeat

>>>'python'*5

'pythonpythonpyhonpythonpython'

>>>[42]*2

[42,42]

5checking

>>>permissions='rw'

>>>'w'inpermissions

True

6internalfunctionsasmin(),max(),len()isuseful

3List-slaveofpython

Listismutable.

>>>list('hello')

['h','e','l','l','e']

********************Basicoperationoflist******************************

allbasicoperationsofsequencecanbeappliedtolist.

1modifythemember

>>>x=[1,1,1]

>>>x[1]=2

>>>x

[1,2,1]

2deletethemember

>>>names=['wangwei','zhangsheng','bill']

>>>delnames[2]

>>>names

['wangwei','zhangsheng']

3shardingassignmeng

>>>name=list('perl')

>>>name[1:

]=list('ython')

>>>name

>>>['p','y','t','h','o','n']

>>>numbers=[1,5]

>>>numbers[1:

1]=[2,3,4]

>>>numbers

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

********************methodoflist***************************************

1append--addingoneobjecttotheendofthelist

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

>>>lst.append(4)

>>>lst

[1,2,3,4]

2x.count(member)

3extend---addinganewlisttotheendofthelist

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

>>>b=[4,5,6]

>>>a.extend(b)

>>>a

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

itisfundamentallydiffrentfrom'+'

extendmethodmodifytheoriginlist,'+'returnanewlist.

4returnthematchingmember'sposition

>>>wang=['wang','wei','shi']

>>>wang.index('wang')

0

5insert--insertnewobjecttothelist

>>>numbers=[1,2,3,5,6,7]

>>>numbers.insert(3,'four')

>>>numbers

[1,2,3,'four',5,6,7]

6pop--delamemberandreturnit.

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

>>>x.pop()---poplastmemberdefaultly

3

7remove--delfirstmatchingmember

>>>x=['wang','wei','wang']

>>>x.remove('wang')

>>>x

['wei','wang']

8reverse--reversethelist,modifybutdonotreturnthenewlist

9sort

>>>x=[1,4,2,3,5]

>>>x.sort()

>>>x

[1,2,3,4,5]

sorted

>>>x=[1,4,2,3,5]

>>>y=sorted(x)

>>>x

[1,4,2,3,5]

>>>y

[1,2,3,4,5]

4TupleString-unmutable

*****************************tuple***************************************

>>>1,2,3

(1,2,3)

>>>(1,2,3)

(1,2,3)

>>>(42,)

(42,)

>>>tuple([1,2,3])

(1,2,3)

>>>tuple('abc')

('a','b','c')

tupleisnotcomplicated.Creatandaccessit.

*****************************string**************************************

allbasicoperationsofsequencecanbeappliedtostring.

formatstring

onlytupleanddictionarycanformatonemorevalues.

>>>format="hello%s.welcome%s"

>>>values=('wei','here')

>>>printformat%values

************************methodofstring***********************************************

1find--searchingsub-string.returnleftindexwhenfindit

2join--mergestringlistwithaspecificcharactor

>>>dirs='','usr','bin','env'

>>>'/'.join(dirs)

'/usr/bin/env'

3lower--returnthelowercaseofthestring

4replace

>>>'thisisatest'.replace('is','eez')

theezeezatest

5split--inversemethodofjoin

>>>'/usr/bin/env'.split('/')

['','usr','bin','env']

5Dictionary--whenindexisnotgood

whenaccessamemberbyname,weusedictionary.wecallthisdatastructuremapping.thevalueofdictionarydonothavespecialsequence,theyallstoreinaspecifickey.thekeycouldbenumber,string,eventuple.

***********************creatandaccess**********************************

>>>phonebook={'alice':

'321','wangwei':

'123'}

>>>phonebook['alice']

creatdictionaryby(key,value)orparaemeters--usefunctiondict()

>>>item=[('name','wangwei'),('age','18')]

>>>d=dict(item)

>>>d['name']

wangwei

>>>d=dict(name='wangwei',age='21')

>>>d={}

>>>d['name']='wangwei'

>>>d['age']='123'

***********************basicoperation*********************************

theoperationissimilartosequence

1len(d)--returnthenumberof(key,value)

2d[k]--returnvalueonkeyk

3d[k]=v--assignment

4deld[k]--deletethespecificmember

5kind--checkspecificmember

>>>phonebook={'wangwei':

123,'zhangsheng':

456}

>>>'myphoneis%('wangwei')s'%phonebook

***********************methodofdictionary******************************

1clear--deleteallmemberofdictionary

>>>y=x

>>>x={}

>>>y

{...}

>>>x.clear()

>>>y

{}

2copy--returnasamedictionary.(shallowcopy,isassociate)

>>>y=x.copy()

deepcopy--deepcopyfunction(isnotassociate)

>>>fromcopyimportdeepcopy

>>>y=x.deepcopy(x)

3fromkeys--creatanewdictionarybyseveralkeys.thevalueisnone

>>>{}.fromkeys(['name','age'])

4get--amorecomfortablewaytoaccessdictionary

>>>d.get('name','N/A')--whenaceessfailed,returnN/Anotnone

6Conditioncycleandotherstatement

*************************morefeature************************************

usepirntx,y,ctopirntmorethanoneexpression

>>>frommathimportsqrtasfoobar

>>>foobar(4)

2.0

morethanoneassignmentoperationcanberunningatthesametime.

>>>x,y,z=1,2,3

>>>x,y=y,x

>>>values

(1,2,4)

>>>x,y,z=values

chainassignment:

>>>x=y=z

augmentedassignment:

>>>x=2

>>>x+=1

>>>x*=2

>>>fnord='foo'

>>>fnord+='bar'

>>>fnord*=2

>>>fnord

'foobarfoobar'

statementblock

runorrunseveraltimewhenconditionistrue.Creatblockbysettingspacebeforestatement.

FalseNone0""()[]{}willberecognizedasFalse

>>>True==1

True

>>>False==0

False

*****************************if****************************************

ifname.endswith('wang'):

print'hello'

print'wangwei'

elifname.endswith('wei'):

print'welcome'

else:

print'thenumberis0'

****************************comparisonoperator**************************

x==y

x

x>y

x>=y

x<=y

x!

=y

xisy

xisnoty

xiny

xnotiny

***************************booleanoperator******************************

ifnumber<=10andnumber>=1:

print'great!

'

else:

print'wrong!

'

***************************assert****************************************

ifnotcondition

crashprogram

wecanuseassertinsteadofit.

>>>age=10

>>>asert0

>>>age=-1

>>>assert0

***************************while*****************************************

>>>x=1

whilex<=100

printx

x+=1

***************************for******************************************************

everymembercanrunthestatementblockonetime

>>>num=[1,2,4,5,7,8]

>>>fornumberinnum:

printnumber

1

2

4

5

7

8

gothroughallthememberofdictionary

d={'x':

1,'y':

2,'z':

3}

forkeyind:

printkey,'correspondsto',d[key]

**************************jumpoutofloop*******************************

frommathimportsqrt

forninrange(99,0,-1):

root=sqrt(n)

ifroot==int(root):

printn

break

*************

forxinseq:

ifcondition1:

continue

dosomething()

*************

whileword:

word=raw_input('plsenter:

')

*************

whiletrue

word=raw_input('plsenter:

')

ifnotword:

break

*************

elsestatementwillrun,onlywhenbreakdoesn'trun

frommathimp

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 解决方案 > 解决方案

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1