《Python语言程序设计》课件-案例1(中英文课件)_第1页
《Python语言程序设计》课件-案例1(中英文课件)_第2页
《Python语言程序设计》课件-案例1(中英文课件)_第3页
《Python语言程序设计》课件-案例1(中英文课件)_第4页
《Python语言程序设计》课件-案例1(中英文课件)_第5页
已阅读5页,还剩154页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Python语言程序设计《案例:利用字典改进猜字游戏》PythonLanguageProgrammingCaseStudy:ImprovingCharadeswithDictionaries案例利用字典改进猜字游戏123456789101112131415161718192021222324252627fromGameimport*#引入Game.py中的所有函数

title='1:我要玩猜字游戏'

title+='\n2:看看每次的猜字情况'

title+='\n3:看看某次的猜字情况'

title+='\n4:退出程序'

logdic={}

times=0

whileTrue:

print(title)

choice=int(input('请输入编号:'))

ifchoice==1:

times+=1

x=eval(input("随机数的最小值:"))

y=eval(input("随机数的最大值:"))

z=eval(input("猜测次数:"))

logList=GuessNumGame(x,y,z)

print(logList)

strLog=",".join(map(str,logList))

logdic[times]=strLog

elifchoice==2:

forkeyinlogdic.keys():

print('第{}次游戏:'.format(key),logdic[key])

elifchoice==3:

cnt=eval(input("请输入第几次:"))

print('第{}次游戏:'.format(cnt),logdic.get(cnt))

elifchoice==4:

quit()testGame.py第6行:定义了一个空字典logdic,用来存储每次游戏的情况。第19行:logdic[times]=strLog,Python的字典利用”Key-Value”(键-值)机制存入数据。第21行:利用for语句遍历字典logdic,采用forkeyinlogdic.keys()字典中的数据是无序的,仅与key有关第25行:利用get方法引用Value:logdic.get(cnt)“logdic[key]”与“logdic.get(cnt)”的区别CaseinpointUsingdictionariestoimprovecharades123456789101112131415161718192021222324252627FromGameimport*#IntroduceallfunctionsinGame.py

title='1:Iwanttoplaycharade'

title+='\n2:Checkthespellingeverytime'

title+='\n3:Lookataguessingsituation'

title+='\n4Exittheprogram'

logdic={}

times=0

whileTrue:

print(title)

Choice=int(input('pleaseenterthenumber:'))

ifchoice==1:

times+=1

x=eval(input("minimumvalueofrandomnumber:"))

y=eval(input("maximumvalueofrandomnumber:"))

z=eval(input("numberofguesses:"))

logList=GuessNumGame(x,y,z)

print(logList)

strLog=",".join(map(str,logList))

logdic[times]=strLog

elifchoice==2:

forkeyinlogdic.keys():

Print('Game{}:'.format(key),logdic[key])

elifchoice==3:

Cnt=eval(input("Pleaseenterthenumberoftimes:"))

Print('Game{}:'.format(cnt),logdic.get(cnt))

elifchoice==4:

quit()testGame.pyLine6:Anemptydictionarylogdicisdefinedtostorethesituationofeachgame.Line19:logdic[times]=strLog,Python'sdictionaryusesthe"KeyValue"mechanismtostoredata.Line21:Usetheforstatementtotraversethedictionarylogdic,andusetheforkeyinlogdic.keys()ThedatainthedictionaryisunorderedandonlyrelatedtothekeyLine25:UsethegetmethodtoreferenceValue:logdic.get(cnt)Thedifferencebetween"logdic[key]"and"logdic.get(cnt)"6logdic={}案例【游戏中的字符串格式化及优化】定义空字典19logdic[times]=strLogKey-Value”(键-值)2122forkeyinlogdic.keys():

print('第{}次游戏:'.format(key),logdic[key])遍历方式25

print('第{}次游戏:'.format(cnt),logdic.get(cnt))Get方法6logdic={}Case[Stringformattingandoptimizationingames]Definetheemptydictionary19logdic[times]=strLogKeyValue2122forkeyinlogdic.keys():

Print('Game{}:'.format(key),logdic[key])traversalmode25

Print('Game{}:'.format(cnt),logdic.get(cnt))Getmethod问题1:字典、列表、元组声明?{}[]()问题2:“logdic[key]”与“logdic.get(cnt)”的区别?提问在没有找到记录时直接引用“logdic[key]”会产生错误退出程序,而利用get方法“logdic.get(cnt)”则会返回“None”Question1:Dictionary,list,tupledeclaration?{}[]()Question2:Whatisthedifferencebetween"logdic[key]"and"logdic.get(cnt)"?AskaquestionWhennorecordisfound,directlyreferencing"logdic[key]"willcauseanerrortoexittheprogram,whileusingthegetmethod"logdic.get(cnt)"willreturn"None"Python语言程序设计《案例:游戏中的字符串格式化及优化》PythonLanguageProgrammingCaseStudy:StringFormattingandOptimizationinGames案例游戏中的字符串格式化及优化对猜字游戏代码进行修改,字符串格式化及优化1234567891011121314151617181920212223242526272829defGuessNumGame(*T):

secret=random.randint(T[0],T[1])

guess=0

tries=0

logList=[]#定义一个列表用来记录用户猜字的过程

print('请你猜一猜从{}到{},会是什么数字?'.format(T[0],T[1]))

print("你只有{}次机会哦!".format(T[2]))

logBetween="猜测范围:{}到{}".format(T[0],T[1])

logTries="猜测机会:{}次".format(T[2])

logTrue="正确的数字为:{}".format(secret)

logList.append([logBetween,logTries,logTrue])

whiletries<T[2]:

guess=eval(input("请输入你猜的数字:"))

tries+=1

ifguess<secret:

print("太小了!!!!!!!!!!")

logList.append(['第{}次'.format(tries),guess,'太小了'])

continue

elifguess>secret:

print("太大了!!!!!!!!!!")

logList.append(['第{}次'.format(tries),guess,'太大了'])

continue

else:

print("恭喜你,猜对了!")

logList.append(['第{}次'.format(tries),guess,'猜对了'])

break

ifguess!=secret:

print("很可惜,你猜错了!")

returnlogListGame.py1234567891011from

import*#引入Game.py中的所有函数

#调用GuessNumGame猜字函数

x

=eval(input("随机数的最小值:"))

y

=eval(input("随机数的最大值:"))

z=eval(input("猜测次数:"))

logList=GuessNumGame(x,y,z)

print(logList)

strLog=

",".join(map(str,logList))

#将列表转换成字符串,后续考虑存储到文件中。

print(strLog)test.pyCaseinpointstringformattingandoptimizationingamesModification,stringformattingandoptimizationofcharadescode1234567891011121314151617181920212223242526272829defGuessNumGame(*T):

secret=random.randint(T[0],T[1])

guess=0

tries=0

logList=[]#Definealisttorecordtheprocessofuserguessing

print('Pleaseguesswhatnumberwillbefrom{}to{}?'format(T[0],T[1]))

print("Youonlyhave{}opportunities!".format(T[2]))

LogBetween="Guessrange:{}to{}".format(T[0],T[1])

LogTries="Guessopportunities:{}times".format(T[2])

LogTrue="Thecorrectnumberis:{}".format(secret)

logList.append([logBetween,logTries,logTrue])

whiletries<T[2]:

guess=eval(input("Pleaseenterthenumberyouguessed:"))

tries+=1

ifguess<secret:

print("Toosmall!!!!!!!!!!")

LogList.append(['the{}th'.format(tries),guess,'toosmall'])

continue

elifguess>secret:

print("Toobig!!!!!!!!!!")

LogList.append(['the{}th'.format(tries),guess,'toobig'])

continue

else:

print("Congratulations,youguesseditright!")

LogList.append(['the{}th'.format(tries),guess,'guessedright'])

break

ifguess!=secret:

print("Unfortunately,youguessedwrong!")

returnlogListGame.py1234567891011from

import*#IntroduceallfunctionsinGame.py

#CallGuessNumGameguessingfunction

x

=eval(input("minimumvalueofrandomnumber:"))

y

=eval(input("maximumvalueofrandomnumber:"))

z

=eval(input("numberofguesses:"))

logList=GuessNumGame(x,y,z)

print(logList)

strLog=

",".join(map(str,logList))

#Convertthelisttoastringforsubsequentconsiderationforstorageinafile.

print(strLog)test.py6print('请你猜一猜从{}到{},会是什么数字?'.format(T[0],T[1]))案例【游戏中的字符串格式化及优化】采用格式化字符串的函数

str.format()的形式,通过{}接收数据,format函数可以接收无限个参数,位置可以不按顺序。如果{}中没有数字,则按顺序获取format函数中的参数值print6print('请你猜一猜从{0}到{1},会是什么数字?'.format(T[0],T[1]))等价于:6print('Pleaseguesswhatnumberwillbefrom{}to{}?'format(T[0],T[1]))Case[Stringformattingandoptimizationingames]Intheformofstr.format(),whichformatsthestring,dataisreceivedthrough{}.Theformatfunctioncanreceiveunlimitedparameters,andthepositionscanbeoutoforder.Iftherearenonumbersin{},gettheparametervaluesintheformatfunctioninorderprint6print('Pleaseguesswhatnumberwillbefrom{0}to{1}?'format(T[0],T[1]))Equivalentto:17logList.append(['第{}次'.format(tries),guess,'太小了'])案例【游戏中的字符串格式化及优化】将format格式化后的字符串放到列表logList中['第{}次'.format(tries),

guess,

'太小了']17LogList.append(['the{}th'.format(tries),guess,'toosmall'])PuttheformatformattedstringintothelistlogList['The{}th'.format(tries),guess,'istoosmall']Case[Stringformattingandoptimizationingames]8strLog=

",".join(map(str,logList))案例【游戏中的字符串格式化及优化】利用map函数将logList中的每个对象都转换成字符串型。map(str,logList)1234567891011from

import*#调用GuessNumGame猜字函数

x

=eval(input("随机数的最小值:"))

y

=eval(input("随机数的最大值:"))

z=eval(input("猜测次数:"))

logList=GuessNumGame(x,y,z)

print(logList)

strLog=

",".join(map(str,logList))

#将列表转换成字符串,后续考虑存储到文件中。

print(strLog)map转换好后,再用join()方法将序列中的元素以指定的字符(,)连接生成一个新的字符",".join(map(str,logList))把logList列表中的所有元素都用逗号(,)隔开,然后拼接在一起,成为一个新的字符串。8strLog=

",".join(map(str,logList))1234567891011from

import*#CallGuessNumGameguessingfunction

x

=eval(input("minimumvalueofrandomnumber:"))

y

=eval(input("maximumvalueofrandomnumber:"))

z

=eval(input("numberofguesses:"))

logList=GuessNumGame(x,y,z)

print(logList)

strLog=

",".join(map(str,logList))

#Convertthelisttoastringforsubsequentconsiderationforstorageinafile.

print(strLog)UsethemapfunctiontoconverteachobjectinthelogListtoastringtype.Afterthemapconversion,usethejoin()methodtoconnecttheelementsinthesequencewiththespecifiedcharacters(,)togenerateanewcharacter",".join(map(str,logList))SeparateallelementsinthelogListwithcommas(,),andthensplicethemtogethertoformanewstring.Case[Stringformattingandoptimizationingames]map(str,logList)问题1:format函数的作用?format函数进行字符串的格式化问题2:下面map(),join()的作用

?提问map(str,logList)“#".join(logList)Question1:Whatdoestheformatfunctiondo?TheformatfunctionformatsthestringQuestion2:Whatarethefunctionsofthefollowingmap()andjoin()?Askaquestionmap(str,logList)“#".join(logList)Python语言程序设计《案例:运行你的第一个程序》PythonLanguageProgrammingCase:RunningYourFirstProgram案例【运行第一个程序】第1行:程序中用“#”表示注释,所有的注释是不执行的。第2行:利用print输出一个字符串,Python的字符串写在双引号(””)或单引号(’’)中。case[Runthefirstprogram]Line1:Commentsareindicatedby"#"intheprogram,andallcommentsarenotexecuted.Line2:Useprinttooutputastring.Pythonstringsarewrittenindoublequotationmarks("")orsinglequotationmarks('').问题1:说说你刚刚学到了哪些内容?(1)注释的方法:#(2)打印:print(“”)

问题2:注释里面的内容是不执行的,对or错?案例【运行第一个程序】Question1:Whathaveyoujustlearned?(1)Commentmethod:#(2)Print:print("")Question2:Thecontentinthecommentisnotexecuted,rightorwrong?case[Runthefirstprogram]********************************你的姓名生日你最喜欢的颜色********************************编写一个简短的程序,打印下面内容:你的姓名、生日以及你最喜欢的颜色。具体格式如下所示:课后练习【任务:打印】********************************YournamebirthdayYourfavoritecolor********************************Writeashortprogramandprintthefollowing:yourname,birthdayandyourfavoritecolor.Thespecificformatisasfollows:[Task:Print]After-schoolexercisesPythonLanguageProgrammingRegularExpressionsforWebParsingCaseinpointRegularExpressionsforWebParsing]1234567importre

f=open('web.txt','r')

web=f.read()

urls=re.findall('https://.*?"',web)

f.close()

forurlinurls:

print(url)123456789101112<divclass="top-nav-websiteapp">

<ahref="/w/app?channel=top-Nav"class="lnk">DownloadXXXwebsiteclient</a><divid="top-nav-appintro"class="more-items">

<pclass="appintrotitle">XXwebsite</p>

<pclass="slogan">Ourblog</p><divclass="download"><aref="/redirect?download=iOS">iPhone</a><span>•</span><ahref="/redirect?download=Ad">Android</a></div></div></div>web.txtLine1:Importtheremodule,whichenablesPythontohaveallregularexpressionfunctions.Inline2,calltheopenmethodofthefiletoopenweb.txt.Inline3,readoutthetextcontentinweb.txtandassignittothewebvariable.getUrls.py279<ahref="/w/app?channel=top-Nav"class="lnk">DownloadXXXwebsiteclient</a><aref="/redirect?download=iOS">iPhone</a><ahref="/redirect?download=Ad">Android</a>

web.txt4urls=re.findall('https://.*?"',web)Inline4,theremoduleprovidesPerlstyleregularexpressionpatterns.Usethefindallfunctiontoobtainallthematchingstringsinthestringweb.Thematchingformatishttps://.*?"。getUrls.pyThebeginningofhttps://meansthathttps://istheprefixtext.Thedot(.)matchesanycharacterexceptthenewlinecharacter"n".Anasterisk(*)meansmatchthepreviouscharacter0timesorinfinitely.Anasterisk(*)followedbyaquestionmark(?).Indicatesanon-greedymatch,i.e.,matchasfewtimesaspossible,e.g.,*?Repeatanynumberoftimes,butaslittleaspossible.Combinationofthreesymbols(.*?)meansmatchanynumberofrepetitions,butusethefewestrepetitionsnecessarytomakethewholematchsuccessful.CaseRegularExpressionsforWebParsing][e.g.]a.*?Bmatchestheshorteststringstartingwithaandendingwithb.Ifitisappliedtoaabab,itwillmatchaabandab.non-greedymatchingCaseRegularExpressionsforWebParsing]279<ahref="/w/app?channel=top-Nav"class="lnk">DownloadXXXwebsiteclient</a><aref="/redirect?download=iOS">iPhone</a><ahref="/redirect?download=Ad">Android</a>

web.txt4urls=re.findall('https://.*?"',web)getUrls.pyhttps://.*?"Indicatesastringthatstartswithhttp://andendswithdoublequotationmarks("),anditisrequiredtomatchthestringwiththeleastrepetition/w/app?channel=top-nav",Soitnolongermatcheshttps:///w/app?channel=top-nav"class=",Althoughclass=isfollowedbydoublequotationmarks("),becauseitisanongreedymode,theonethatmatchessuccessfullyforthefirsttimeisselected.I.ehttps:///w/app?channel=top-nav"。CaseRegularExpressionsforWebParsing]Python语言程序设计【正则表达式进行网页解析】案例【正则表达式进行网页解析】1234567importre

f=open('web.txt','r')

web=f.read()

urls=re.findall('https://.*?"',web)

f.close()

forurlinurls:

print(url)123456789101112<divclass="top-nav-websiteapp"><ahref="/w/app?channel=top-nav"class="lnk">下载某某网站客户端</a><divid="top-nav-appintro"class="more-items"><pclass="appintro-title">某某网站</p><pclass="slogan">我们的部落格</p><divclass="download"><aref="/redirect?download=iOS">iPhone</a><span>•</span><ahref="/redirect?download=Ad">Android</a></div></div></div>web.txt第1行,导入re模块,re模块使Python语言拥有全部的正则表达式功能。第2行,调用文件的open方法,打开web.txt。第3行,将web.txt中的文本内容读取出来,赋值给web变量。getUrls.py279<ahref="/w/app?channel=top-nav"class="lnk">下载某某网站客户端</a><aref="/redirect?download=iOS">iPhone</a><ahref="/redirect?download=Ad">Android</a>

web.txt4urls=re.findall('https://.*?"',web)第4行,re模块提供

Perl风格的正则表达式模式。利用findall函数获取字符串web中所有匹配的字符串。匹配格式为:https://.*?"。getUrls.pyhttps://开头表示以https://为前缀文本。点(.)匹配任意除换行符“\n”外的字符。星号(*)表示匹配前一个字符0次或无限次。星号(*)后跟问号(?)表示非贪婪匹配,即尽可能少的匹配,如*?重复任意次,但尽可能少重复。三个符号组合(.*?)表示匹配任意数量的重复,但是在能使整个匹配成功的前提下使用最少的重复。案例【正则表达式进行网页解析】【例如】a.*?b匹配最短的,以a开始,以b结束的字符串。如果把它应用于aabab的话,它会匹配aab和ab。案例【正则表达式进行网页解析】非贪婪匹配案例【正则表达式进行网页解析】279<ahref="/w/app?channel=top-nav"class="lnk">下载某某网站客户端</a><aref="/redirect?download=iOS">iPhone</a><ahref="/redirect?download=Ad">Android</a>

web.txt4urls=re.findall('https://.*?"',web)getUrls.pyhttps://.*?"表示以http://开始,以双引号(“)结束的字符串,而且要求匹配重复最少的。上例中首先匹配到/w/app?channel=top-nav",所以不再匹配/w/app?channel=top-nav"class=",虽然class=后面也有双引号(“),但是因为是非贪婪模式,所以选择第一次匹配成功的那个。即/w/app?channel=top-nav"。Python语言程序设计【正则表达式进行网页解析】案例【正则表达式进行网页解析】1234567importre

f=open('web.txt','r')

web=f.read()

urls=re.findall('https://.*?"',web)

f.close()

forurlinurls:

print(url)123456789101112<divclass="top-nav-websiteapp"><ahref="/w/app?channel=top-nav"class="lnk">下载某某网站客户端</a><divid="top-nav-appintro"class="more-items"><pclass="appintro-title">某某网站</p><pclass="slogan">我们的部落格</p><divclass="download"><aref="/redirect?download=iOS">iPhone</a><span>•</span><ahref="/redirect?download=Ad">Android</a></div></div></div>web.txt第1行,导入re模块,re模块使Python语言拥有全部的正则表达式功能。第2行,调用文件的open方法,打开web.txt。第3行,将web.txt中的文本内容读取出来,赋值给web变量。getUrls.py279<ahref="/w/app?channel=top-nav"class="lnk">下载某某网站客户端</a><aref="/redirect?download=iOS">iPhone</a><ahref="/redirect?download=Ad">Android</a>

web.txt4urls=re.findall('https://.*?"',web)第4行,re模块提供

Perl风格的正则表达式模式。利用findall函数获取字符串web中所有匹配的字符串。匹配格式为:https://.*?"。getUrls.pyhttps://开头表示以https://为前缀文本。点(.)匹配任意除换行符“\n”外的字符。星号(*)表示匹配前一个字符0次或无限次。星号(*)后跟问号(?)表示非贪婪匹配,即尽可能少的匹配,如*?重复任意次,但尽可能少重复。三个符号组合(.*?)表示匹配任意数量的重复,但是在能使整个匹配成功的前提下使用最少的重复。案例【正则表达式进行网页解析】【例如】a.*?b匹配最短的,以a开始,以b结束的字符串。如果把它应用于aabab的话,它会匹配aab和ab。案例【正则表达式进行网页解析】非贪婪匹配案例【正则表达式进行网页解析】279<ahref="/w/app?channel=top-nav"class="lnk">下载某某网站客户端</a><aref="/redirect?download=iOS">iPhone</a><ahref="/redirect?download=Ad">Android</a>

web.txt4urls=re.findall('https://.*?"',web)getUrls.pyhttps://.*?"表示以http://开始,以双引号(“)结束的字符串,而且要求匹配重复最少的。上例中首先匹配到/w/app?channel=top-nav",所以不再匹配/w/app?channel=top-nav"class=",虽然class=后面也有双引号(“),但是因为是非贪婪模式,所以选择第一次匹配成功的那个。即/w/app?channel=top-nav"。Python语言程序设计《案例:用函数的方法》PythonLanguageProgrammingTheCase:AFunctionalApproach案例【用函数的方法输出你的第一程序】第2行:用def关键字定义了一个名为Hello的函数,该函数没有任何参数。第3行:使用缩进的方法来规定函数体的范围123456#函数定义

defHello():

print("Helloworld!")

#函数调用

Hello()第6行:直接调用Hello()函数,就可以打印出“Helloworld!”未用函数使用函数Case[Outputyourfirstprogramasafunction]Line2:AfunctionnamedHelloisdefinedwiththedefkeyword,whichhasnoparameters.Line3:Useindentationtospecifythescopeofthefunctionbody123456#functiondefinition

defHello():

print("Helloworld!")

#functioncall

Hello()Line6:CalltheHello()functiondirectlytoprint"Helloworld!"unusedfunctionUsingthefunction问题1:函数的定义用哪个关键字?def问题2:如何规定函数体的范围?提问缩进Question1:Whichkeywordisusedforthedefinitionofafunction?defQuestion2:Howdoyouspecifythescopeofafunctionbody?AskaquestionIndent案例【用函数的方法定义正方形的面积】第1行:定义计算正方形面积的函数calcSquare,形参x为正方形边长。第2行:表达式x**2表示x的2次方。1234567defcalcSquare(x):

returnx**2

#调用calcSquare函数

a=float(input("输入正方形的边长:"))

Area=calcSquare(a)

print("您输入的正方形边长为"+str(a)+",正方形面积为:“+str(Area))第6行:直接调用calcSquare函数。先定义,后使用!!![Definetheareaofasquareintermsofafunction]Line1:DefinethefunctioncalcSquaretocalculatethesquarearea,andtheformalparameterxisthesquaresidelength.Line2:Theexpressionx**2representsthepower2ofx.1234567defcalcSquare(x):

returnx**2

#CallcalcSquarefunction

A=float(input("Enterthesidelengthofthesquare:"))

Area=calcSquare(a)

Print("Thesidelengthofthesquareyouenteredis"+str(a)+",andthesquareareais:"+str(Area))Line6:CallthecalcSquarefunctiondirectly.Defineit,thenuseit!!!!Case问题1:Python中缩进()个空格?A.1B.4 C.6D.2问题2:函数必须先定义再使用?提问Question1:Indent(

)spacesinPython?A.1B.4 C.6D.2Question2:Mustfunctionsbedefinedbeforetheycanbeused?Askaquestion案例【用函数的方法定义猜字游戏】1234567891011121314151617181920defGuessNumGame(m,n,times):

importrandom

secret=random.randint(m,n)

guess=0

tries=0

print("请你猜一猜从"+str(m)+"到"+str(n)+",会是什么数字?")

print("你只有"+str(times)+"次机会哦!")

whileguess!=secretandtries<times:

guess=eval(input("请输入你猜的数字:"))

ifguess==secret:

print("猜对了,恭喜你!!!!")

break

elifguess<secret:

print("太小了!!!!!")

else:

print("太大了!!!!!")

tries+=1

iftries>=timesandguess!=secret:

print("次数用完,很遗憾你没猜中!!!!!")

print(secret)第1行:定义三个参数m,n,times,分别表示随机数的最小值,随机数的最大值,猜测次数。第6、7行:提示用户猜测的数据范围和可以猜测的次数。str()函数将数字转换成字符串型。Game.py[Definecharadesintermsoffunctions]1234567891011121314151617181920defGuessNumGame(m,n,times):

importrandom

secret=random.randint(m,n)

guess=0

tries=0

Print("Pleaseguessthenumberfrom"+str(m)+"to"+str(n)+"?)

Print("Youonlyhave"+str(times)+"secondchance!")

whileguess!=secretandtries<times:

Guess=eval(input("Pleaseenterthenumberyouguessed:"))

ifguess==secret:

Print("Guessright,congratulations!!!")

break

elifguess<secret:

Print("Toosmall!!!!")

else:

Print("Toobig!!!!")

tries+=1

iftries>=timesandguess!=secret:

Print("Weranoutoftimes,I'msorryyoumissed!!!!")

print(secret)Line1:Definethreeparameters,m,n,andtimes,whichrespectivelyrepresenttheminimumvalueofrandomnumber,themaximumvalueofrandomnumber,andthenumberofguesses.Lines6and7:prompttheusertoguessthedatarangeandthenumberoftimeshecanguess.Thestr()functionconvertsanumbertoastring.Game.pyCase案例【用函数的方法定义猜字游戏】123456fromGameimport*#引入Game.py中的所有函数

#调用GuessNumGame猜字函数

x=eval(input("随机数的最小值:"))

y=eval(input("随机数的最大值:"))

z=eval(input("猜测次数:"))

GuessNumGame(x,y,z)testGame.py第1行:fromGameimport*表示从Game.py中引入所有函数,其中星*号代表所有函数。这里也可以写成:fromGameimportGuessNumGame第6行:直接调用GuessNumGame函数,并传递三个实参给它。完成一次游戏的全过程。[Definecharadesintermsoffunctions]123456FromGameimport*#IntroduceallfunctionsinGame.py

#CallGuessNumGameguessingfunction

X=eval(input("minimumvalueofrandomnumber:"))

Y=eval(input("maximumvalueofrandomnumber:"))

Z=eval(input("numberofguesses:"))

GuessNumGame(x,y,z)testGame.pyLine1:fromGameimport*indicatesthatallfunctionsareintroducedfromGame.py,andthestar*indicatesallfunctions.Itcanalsobewrittenas:fromGameimportGuessNumGameLine6:CalltheGuessNumGamefunctiondirectlyandpassthreeactualparameterstoit.Completethewholeprocessofagame.Case函数的作用?案例【用函数的方法定义猜字游戏】Whatisthefunction'sfunction?[Definecharadesintermsoffunctions]Case问题.关于函数的目的,以下说明不正确的是()A.提高程序的执行效率B.减少程序文件所占用的内存C.提高程序的可读性D.提高程序的开发效率提问1.代码的复用2.可读性更好3.开发效率高Question.Withrespecttothepurposeofafunction,thefollowingstatementisincorrect()A.ImproveprogramexecutionefficiencyB.ReducethememoryoccupiedbyprogramfilesC.ImproveprogramreadabilityD.ImprovetheefficiencyofprogramdevelopmentAskaquestion1.codereuse2.Betterreadability3.HighlyefficientdevelopmentPython语言程序设计《案例:利用文本文件读写存储游戏过程日志》PythonLanguageProgrammingCase:Usingtextfilestoreadandwritestoredgameprocedurelogs.案例利用文本文件读写存储游戏过程日志12345678910111213141516#readfile函数

defreadfile(filename):

fp=open(filename,'r')#利用r(read)方式

flist=fp.readlines()#按换行符分割,将每行作为一个元素存入列表flist

fp.close()

returnflist

#writefile函数

defwritefile(filename,log):

fp=open(filename,'w')#利用w(write)方式

fp.writelines(log)#把log字符串写入文件filename中

fp.close()

#appendfile函数

defappendfile(filename,log):

fp=open(filename,'a')#利用a(append)方式

fp.writelines(log)#将log字符串添加到文件filename中

fp.close()FileTools.pyFileTools.py中定义了三个函数,分别是:readfile读文件、writefile写文件、appendfile向文件添加内容。这三个函数实际上是封装了Python的open、readlines和writelines函数。CaseReadingandwritingstoredgameprocedurelogsusingtextfiles12345678910111213141516#readfilefunction

defreadfile(filename):

fp=open(filename,'r')#Usether(read)method

flist=fp.readlines()#Splitbynewlinecharacter,andsaveeachlineasanelementinthelistflist

fp.close()

returnflist

#Writefilefunction

defwritefile(filename,log):

fp=open(filename,'w')#Usew(write)mode

fp.writelines(log)#Writethelogstringtothefilefilename

fp.close()

#Appendfilefunction

defappendfile(filename,log):

fp=open(filename,'a')#Usea(append)method

fp.writelines(log)#Addlogstringtofilefilename

fp.close()FileTools.pyFileTools.pydefinesthreefunctions:readfilereadfile,writefilewritefile,appendfileaddcontenttofile.ThesethreefunctionsactuallyencapsulatePython'sopen,

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论