SolutionsChapter 10.docx
- 文档编号:4393243
- 上传时间:2022-12-01
- 格式:DOCX
- 页数:12
- 大小:18.64KB
SolutionsChapter 10.docx
《SolutionsChapter 10.docx》由会员分享,可在线阅读,更多相关《SolutionsChapter 10.docx(12页珍藏版)》请在冰豆网上搜索。
SolutionsChapter10
Solutions-Chapter10
10-1:
LearningPython
Openablankfileinyourtexteditorandwriteafewlinessummarizingwhatyou’velearnedaboutPythonsofar.Starteachlinewiththephrase InPythonyoucan… Savethefileaslearning_python.txt inthesamedirectoryasyourexercisesfromthischapter.Writeaprogramthatreadsthefileandprintswhatyouwrotethreetimes.Printthecontentsoncebyreadingintheentirefile,oncebyloopingoverthefileobject,andoncebystoringthelinesinalistandthenworkingwiththemoutsidethe with block.
learning_python.txt:
InPythonyoucanstoreasmuchinformationasyouwant.
InPythonyoucanconnectpiecesofinformation.
InPythonyoucanmodelreal-worldsituations.
learning_python.py:
filename='learning_python.txt'
print("---Readingintheentirefile:
")
withopen(filename)asf:
contents=f.read()
print(contents)
print("\n---Loopingoverthelines:
")
withopen(filename)asf:
forlineinf:
print(line.rstrip())
print("\n---Storingthelinesinalist:
")
withopen(filename)asf:
lines=f.readlines()
forlineinlines:
print(line.rstrip())
Output:
---Readingintheentirefile:
InPythonyoucanstoreasmuchinformationasyouwant.
InPythonyoucanconnectpiecesofinformation.
InPythonyoucanmodelreal-worldsituations.
---Loopingoverthelines:
InPythonyoucanstoreasmuchinformationasyouwant.
InPythonyoucanconnectpiecesofinformation.
InPythonyoucanmodelreal-worldsituations.
---Storingthelinesinalist:
InPythonyoucanstoreasmuchinformationasyouwant.
InPythonyoucanconnectpiecesofinformation.
InPythonyoucanmodelreal-worldsituations.
10-2:
LearningC
Youcanusethe replace() methodtoreplaceanywordinastringwithadifferentword.Here’saquickexampleshowinghowtoreplace 'dog' with 'cat' inasentence:
>>>message="Ireallylikedogs."
>>>message.replace('dog','cat')
'Ireallylikecats.'
Readineachlinefromthefileyoujustcreated, learning_python.txt,andreplacetheword Pythonwiththenameofanotherlanguage,suchas C.Printeachmodifiedlinetothescreen.
filename='learning_python.txt'
withopen(filename)asf:
lines=f.readlines()
forlineinlines:
#Getridofnewline,thenreplacePythonwithC.
line=line.rstrip()
print(line.replace('Python','C'))
Output:
InCyoucanstoreasmuchinformationasyouwant.
InCyoucanconnectpiecesofinformation.
InCyoucanmodelreal-worldsituations.
Youcanuse rstrip() and replace() onthesameline.Thisiscalled chaining methods.Inthefollowingcodethenewlineisstrippedfromtheendofthelineandthen Python isreplacedby C.Theoutputisidenticaltothecodeshownabove.
filename='learning_python.txt'
withopen(filename)asf:
lines=f.readlines()
forlineinlines:
#Getridofnewline,thenreplacePythonwithC.
print(line.rstrip().replace('Python','C'))
10-3:
Guest
Writeaprogramthatpromptstheuserfortheirname.Whentheyrespond,writetheirnametoafilecalled guest.txt.
name=input("What'syourname?
")
filename='guest.txt'
withopen(filename,'w')asf:
f.write(name)
Output:
What'syourname?
eric
guest.txt:
eric
10-4:
GuestBook
Writea while loopthatpromptsusersfortheirname.Whentheyentertheirname,printagreetingtothescreenandaddalinerecordingtheirvisitinafilecalled guest_book.txt.Makesureeachentryappearsonanewlineinthefile.
filename='guest_book.txt'
print("Enter'quit'whenyouarefinished.")
whileTrue:
name=input("\nWhat'syourname?
")
ifname=='quit':
break
else:
withopen(filename,'a')asf:
f.write(name+"\n")
print("Hi"+name+",you'vebeenaddedtotheguestbook.")
Output:
Enter'quit'whenyouarefinished.
What'syourname?
eric
Hieric,you'vebeenaddedtotheguestbook.
What'syourname?
willie
Hiwillie,you'vebeenaddedtotheguestbook.
What'syourname?
ever
Hiever,you'vebeenaddedtotheguestbook.
What'syourname?
erin
Hierin,you'vebeenaddedtotheguestbook.
What'syourname?
quit
guest_book.txt:
eric
willie
ever
erin
10-5:
ProgrammingPoll
Writea while loopthataskspeoplewhytheylikeprogramming.Eachtimesomeoneentersareason,addtheirreasontoafilethatstoresalltheresponses.
filename='programming_poll.txt'
responses=[]
whileTrue:
response=input("\nWhydoyoulikeprogramming?
")
responses.append(response)
continue_poll=input("Wouldyouliketoletsomeoneelserespond?
(y/n)")
ifcontinue_poll!
='y':
break
withopen(filename,'a')asf:
forresponseinresponses:
f.write(response+"\n")
Output:
Whydoyoulikeprogramming?
Programmerscanbuildalmostanythingtheycanimagine.
Wouldyouliketoletsomeoneelserespond?
(y/n)y
Whydoyoulikeprogramming?
It'sreallyfun,andreallysatisfying.
Wouldyouliketoletsomeoneelserespond?
(y/n)y
Whydoyoulikeprogramming?
Itjustnevergetsold.
Wouldyouliketoletsomeoneelserespond?
(y/n)n
programming_poll.txt:
Programmerscanbuildalmostanythingtheycanimagine.
It'sreallyfun,andreallysatisfying.
Itjustnevergetsold.
10-6:
Addition
Onecommonproblemwhenpromptingfornumericalinputoccurswhenpeopleprovidetextinsteadofnumbers.Whenyoutrytoconverttheinputtoan int,you’llgeta ValueError.Writeaprogramthatpromptsfortwonumbers.Addthemtogetherandprinttheresult.CatchtheTypeError ifeitherinputvalueisnotanumber,andprintafriendlyerrormessage.Testyourprogrambyenteringtwonumbersandthenbyenteringsometextinsteadofanumber.
try:
x=input("Givemeanumber:
")
x=int(x)
y=input("Givemeanothernumber:
")
y=int(y)
exceptValueError:
print("Sorry,Ireallyneededanumber.")
else:
sum=x+y
print("Thesumof"+str(x)+"and"+str(y)+"is"+str(sum)+".")
Outputwithtwointegers:
Givemeanumber:
23
Givemeanothernumber:
47
Thesumof23and47is70.
Outputwithnon-numericalinput:
Givemeanumber:
23
Givemeanothernumber:
fred
Sorry,Ireallyneededanumber.
10-7:
AdditionCalculator
WrapyourcodefromExercise10-6ina while loopsotheusercancontinueenteringnumberseveniftheymakeamistakeandentertextinsteadofanumber.
print("Enter'q'atanytimetoquit.\n")
whileTrue:
try:
x=input("\nGivemeanumber:
")
ifx=='q':
break
x=int(x)
y=input("Givemeanothernumber:
")
ify=='q':
break
y=int(y)
exceptValueError:
print("Sorry,Ireallyneededanumber.")
else:
sum=x+y
print("Thesumof"+str(x)+"and"+str(y)+"is"+str(sum)+".")
Output:
Enter'q'atanytimetoquit.
Givemeanumber:
23
Givemeanothernumber:
47
Thesumof23and47is70.
Givemeanumber:
three
Sorry,Ireallyneededanumber.
Givemeanumber:
3
Givemeanothernumber:
five
Sorry,Ireallyneededanumber.
Givemeanumber:
-12
Givemeanothernumber:
20
Thesumof-12and20is8.
Givemeanumber:
q
10-8:
CatsandDogs
Maketwofiles, cats.txt and dogs.txt.Storeatleastthreenamesofcatsinthefirstfileandthreenamesofdogsinthesecondfile.Writeaprogramthattriestoreadthesefilesandprintthecontentsofthefiletothescreen.Wrapyourcodeina try-except blocktocatchthe FileNotFounderror,andprintafriendlymessageifafileismissing.Moveoneofthefilestoadifferentlocationonyoursystem,andmakesurethecodeinthe except blockexecutesproperly.
cats.txt:
henry
clarence
mildred
dogs.txt:
willie
annahootz
summit
cats_and_dogs.py:
filenames=['cats.txt','dogs.txt']
forfilenameinfilenames:
print("\nReadingfile:
"+filename)
try:
withopen(filename)asf:
contents=f.read()
print(contents)
exceptFileNotFoundError:
print("Sorry,Ican'tfindthatfile.")
Outputwithbothfiles:
Readingfile:
cats.txt
henry
clarence
mildred
Readingfile:
dogs.txt
willie
annahootz
summit
Outputaftermoving cats.txt:
Readingfile:
cats.txt
Sorry,Ican'tfindthatfile.
Readingfile:
dogs.txt
willie
annahootz
summit
10-9:
SilentCatsandDogs
Modifyyour except blockinExercise10-8tofailsilentlyifeitherfileismissing.
filenames=['cats.txt','dogs.txt']
forfilenameinfilenames:
try:
withopen(filename)asf:
contents=f.read()
exceptFileNotFoundError:
pass
else:
print("\nReadingfile:
"+filename)
print(contents)
Outputwhenbothfilesexist:
Readingfile:
cats.txt
henry
clarence
mildred
Readingfile:
dogs.txt
willie
annahootz
summit
Outputwhen cats.txt hasbeenmoved:
Readingfile:
dogs.txt
willie
annahootz
summit
10-11:
FavoriteNumber
Writeaprogramthatpromptsfortheuser’sfavoritenumber.Use json.dump() tostorethisnumberinafile.Writeaseparateprogramthatreadsinthisvalueandprintsthemessage,“Iknowyourfavoritenumber!
It’s_____.”
favorite_number_write.py:
importjson
number=input("What'syourfavoritenumber?
")
withopen('favorite_number.json','w')asf:
json.dump(number,f)
print("Thanks!
I'llrememberthat.")
Output:
What'syourfavoritenumber?
42
Thanks!
I'llrememberthat.
favorite_number_read.py:
importjson
withopen('favorite_number.json')asf:
number=json.load(f)
print("Iknowyourfavoritenumber!
It's"+str(number)+".")
Output:
Iknowyourfavoritenumber!
It's42.
10-12:
FavoriteNumberRemembered
CombinethetwoprogramsfromExercise10-11intoonefile.Ifthenumberisalreadystored,reportthefavoritenumbertotheuser.Ifnot,promptfortheuser’sfavoritenumberandstoreitinafile.Runtheprogramtwicetoseethatitworks.
importjson
try:
withopen('favorite_number.json')asf:
number=json.load(f)
exceptFileNotFoundError:
n
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Solutions Chapter 10