您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 信息化管理 > PYTHON简明教程 源代码及语言参考
4.1使用变量和字面意义上的常量i=5printii=i+1printis='''Thisisamulti-linestring.Thisisthesecondline.'''prints5.1使用表达式length=5breadth=2area=length*breadthprint'Areais',areaprint'Perimeteris',2*(length+breadth)6.1使用if语句number=23guess=int(raw_input('Enteraninteger:'))ifguess==number:print'Congratulations,youguessedit.'#Newblockstartshereprint(butyoudonotwinanyprizes!)#Newblockendshereelifguessnumber:print'No,itisalittlehigherthanthat'#Anotherblockelse:#Youcandowhateveryouwantinablock...print'No,itisalittlelowerthanthat'#youmusthaveguessnumbertoreachhereprint'Done'#Thislaststatementisalwaysexecuted,aftertheifstatementisexecuted6.2使用while语句number=23running=Truewhilerunning:guess=int(raw_input('Enteraninteger:'))ifguess==number:print'Congratulations,youguessedit.'running=False#thiscausesthewhilelooptostopelifguessnumber:print'No,itisalittlehigherthanthat'else:print'No,itisalittlelowerthanthat'else:print'Thewhileloopisover.'print'Done'6.3使用for语句foriinrange(1,5):printielse:print'Theforloopisover'6.4使用break语句whileTrue:s=raw_input('Entersomething:')ifs=='quit':breakprint'Lengthofthestringis',len(s)print'Done'6.5使用continue语句whileTrue:s=raw_input('Entersomething:')ifs=='quit':breakiflen(s)3:continueprint'Inputisofsufficientlength'7.1定义函数defsayHello():print'HelloWorld!'#blockbelongingtothefunctionsayHello()#callthefunction7.2使用函数形参defprintMax(a,b):ifab:printa,'ismaximum'else:printb,'ismaximum'printMax(3,4)#directlygiveliteralvaluesx=5y=7printMax(x,y)#givevariablesasarguments7.3使用局部变量deffunc(x):print'xis',xx=2print'Changedlocalxto',xx=50func(x)print'xisstill',x7.4使用global语句deffunc():globalxprint'xis',xx=2print'Changedlocalxto',xx=50func()print'Valueofxis',x7.5使用默认参数值defsay(message,times=1):printmessage*timessay('Hello')say('World',5)7.6使用关键参数deffunc(a,b=5,c=10):print'ais',a,'andbis',b,'andcis',cfunc(3,7)func(25,c=24)func(c=50,a=100)7.7使用字面意义上的语句defmaximum(x,y):ifxy:returnxelse:returnyprintmaximum(2,3)7.8使用DocStringsdefprintMax(x,y):'''Printsthemaximumoftwonumbers.Thetwovaluesmustbeintegers.'''x=int(x)#converttointegers,ifpossibley=int(y)ifxy:printx,'ismaximum'else:printy,'ismaximum'printMax(3,5)printprintMax.__doc__8.1使用sys模块importsysprint'Thecommandlineargumentsare:'foriinsys.argv:printiprint'\n\nThePYTHONPATHis',sys.path,'\n'8.2使用模块的__name__if__name__=='__main__':print'Thisprogramisbeingrunbyitself'else:print'Iambeingimportedfromanothermodule'8.3如何创建你自己的模块defsayhi():print'Hi,thisismymodulespeaking.'version='0.1'#Endofmymodule.pyimportmymodulemymodule.sayhi()print'Version',mymodule.version8.4使用dir函数importsysdir(sys)#getlistofattributesforsysmodule['__displayhook__','__doc__','__excepthook__','__name__','__stderr__','__stdin__','__stdout__','_getframe','api_version','argv'...dir()#getlistofattributesforcurrentmodule['__builtins__','__doc__','__name__','sys']a=5#createanewvariable'a'dir()['__builtins__','__doc__','__name__','a','sys']dela#delete/removeanamedir()['__builtins__','__doc__','__name__','sys']9.1使用列表shoplist=['apple','mango','carrot','banana']##Thisismyshoppinglistprint'Ihave',len(shoplist),'itemstopurchase.'print'Theseitemsare:',#Noticethecommaatendofthelineforiteminshoplist:printitem,print'\nIalsohavetobuyrice.'shoplist.append('rice')print'Myshoppinglistisnow',shoplistprint'Iwillsortmylistnow'shoplist.sort()print'Sortedshoppinglistis',shoplistprint'ThefirstitemIwillbuyis',shoplist[0]olditem=shoplist[0]delshoplist[0]print'Iboughtthe',olditemprint'Myshoppinglistisnow',shoplist9.2使用元组zoo=('wolf','elephant','penguin')print'Numberofanimalsinthezoois',len(zoo)new_zoo=('monkey','dolphin',zoo)print'Numberofanimalsinthenewzoois',len(new_zoo)print'Allanimalsinnewzooare',new_zooprint'Animalsbroughtfromoldzooare',new_zoo[2]print'Lastanimalbroughtfromoldzoois',new_zoo[2][2]9.3使用元组输出age=22name='Swaroop'print'%sis%dyearsold'%(name,age)print'Whyis%splayingwiththatpython?'%name9.4使用字典ab={'Swaroop':'swaroopch@byteofpython.info','Larry':'larry@wall.org','Matsumoto':'matz@ruby-lang.org','Spammer':'spammer@hotmail.com'}#'ab'isshortfor'a'ddress'b'ookprintSwaroop'saddressis%s%ab['Swaroop']ab['Guido']='guido@python.org'#Addingakey/valuepairdelab['Spammer']#Deletingakey/valuepairprint'\nThereare%dcontactsintheaddress-book\n'%len(ab)forname,addressinab.items():print'Contact%sat%s'%(name,address)if'Guido'inab:#ORab.has_key('Guido')print\nGuido'saddressis%s%ab['Guido']9.5使用序列shoplist=['apple','mango','carrot','banana']print'Item0is',shoplist[0]#Indexingor'Subscription'operationprint'Item1is',shoplist[1]print'Item2is',shoplist[2]print'Item3is',shoplist[3]print'Item-1is',shoplist[-1]print'Item-2is',shoplist[-2]print'Item1to3is',shoplist[1:3]#Slicingonalistprint'Item2toendis',shoplist[2:]print'Item1to-1is',shoplist[1:-1]print'Itemstarttoendis',shoplist[:]name='swaroop'#Slicingonastringprint'characters1to3is',name[1:3]print'characters2toendis',name[2:]print'characters1to-1is',name[1:-1]print'charactersstarttoendis',name[:]9.6对象与参考print'SimpleAssignment'shoplist=['apple','mango','carrot','banana']mylist=shoplist#mylistisjustanot
本文标题:PYTHON简明教程 源代码及语言参考
链接地址:https://www.777doc.com/doc-3198693 .html