SolutionsChapter 8.docx

上传人:b****7 文档编号:10250987 上传时间:2023-02-09 格式:DOCX 页数:14 大小:19.09KB
下载 相关 举报
SolutionsChapter 8.docx_第1页
第1页 / 共14页
SolutionsChapter 8.docx_第2页
第2页 / 共14页
SolutionsChapter 8.docx_第3页
第3页 / 共14页
SolutionsChapter 8.docx_第4页
第4页 / 共14页
SolutionsChapter 8.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

SolutionsChapter 8.docx

《SolutionsChapter 8.docx》由会员分享,可在线阅读,更多相关《SolutionsChapter 8.docx(14页珍藏版)》请在冰豆网上搜索。

SolutionsChapter 8.docx

SolutionsChapter8

Solutions-Chapter8

8-1:

Message

Writeafunctioncalled display_message() thatprintsonesentencetellingeveryonewhatyouarelearningaboutinthischapter.Callthefunction,andmakesurethemessagedisplayscorrectly.

defdisplay_message():

"""DisplayamessageaboutwhatI'mlearning."""

msg="I'mlearningtostorecodeinfunctions."

print(msg)

display_message()

Output:

I'mlearningtostorecodeinfunctions.

8-2:

FavoriteBook

Writeafunctioncalled favorite_book() thatacceptsoneparameter, title.Thefunctionshouldprintamessage,suchas OneofmyfavoritebooksisAliceinWonderland. Callthefunction,makingsuretoincludeabooktitleasanargumentinthefunctioncall.

deffavorite_book(title):

"""Displayamessageaboutsomeone'sfavoritebook."""

print(title+"isoneofmyfavoritebooks.")

favorite_book('TheAbstractWild')

Output:

TheAbstractWildisoneofmyfavoritebooks.

8-3:

T-Shirt

Writeafunctioncalled make_shirt() thatacceptsasizeandthetextofamessagethatshouldbeprintedontheshirt.Thefunctionshouldprintasentencesummarizingthesizeoftheshirtandthemessageprintedonit.

Callthefunctiononceusingpositionalargumentstomakeashirt.Callthefunctionasecondtimeusingkeywordarguments.

defmake_shirt(size,message):

"""Summarizetheshirtthat'sgoingtobemade."""

print("\nI'mgoingtomakea"+size+"t-shirt.")

print('Itwillsay,"'+message+'"')

make_shirt('large','IlovePython!

')

make_shirt(message="Readabilitycounts.",size='medium')

Output:

I'mgoingtomakealarget-shirt.

Itwillsay,"IlovePython!

"

I'mgoingtomakeamediumt-shirt.

Itwillsay,"Readabilitycounts."

8-4:

LargeShirts

Modifythe make_shirt() functionsothatshirtsarelargebydefaultwithamessagethatreads IlovePython.Makealargeshirtandamediumshirtwiththedefaultmessage,andashirtofanysizewithadifferentmessage.

defmake_shirt(size='large',message='IlovePython!

'):

"""Summarizetheshirtthat'sgoingtobemade."""

print("\nI'mgoingtomakea"+size+"t-shirt.")

print('Itwillsay,"'+message+'"')

make_shirt()

make_shirt(size='medium')

make_shirt('small','Programmersareloopy.')

Output:

I'mgoingtomakealarget-shirt.

Itwillsay,"IlovePython!

"

I'mgoingtomakeamediumt-shirt.

Itwillsay,"IlovePython!

"

I'mgoingtomakeasmallt-shirt.

Itwillsay,"Programmersareloopy."

8-5:

Cities

Writeafunctioncalled describe_city() thatacceptsthenameofacityanditscountry.Thefunctionshouldprintasimplesentence,suchas ReykjavikisinIceland. Givetheparameterforthecountryadefaultvalue.Callyourfunctionforthreedifferentcities,atleastoneofwhichisnotinthedefaultcountry.

defdescribe_city(city,country='chile'):

"""Describeacity."""

msg=city.title()+"isin"+country.title()+"."

print(msg)

describe_city('santiago')

describe_city('reykjavik','iceland')

describe_city('puntaarenas')

Output:

SantiagoisinChile.

ReykjavikisinIceland.

PuntaArenasisinChile.

8-6:

CityNames

Writeafunctioncalled city_country() thattakesinthenameofacityanditscountry.Thefunctionshouldreturnastringformattedlikethis:

“Santiago,Chile”

Callyourfunctionwithatleastthreecity-countrypairs,andprintthevaluethat’sreturned.

defcity_country(city,country):

"""Returnastringlike'Santiago,Chile'."""

return(city.title()+","+country.title())

city=city_country('santiago','chile')

print(city)

city=city_country('ushuaia','argentina')

print(city)

city=city_country('longyearbyen','svalbard')

print(city)

Output:

Santiago,Chile

Ushuaia,Argentina

Longyearbyen,Svalbard

8-7:

Album

Writeafunctioncalled make_album() thatbuildsadictionarydescribingamusicalbum.Thefunctionshouldtakeinanartistnameandanalbumtitle,anditshouldreturnadictionarycontainingthesetwopiecesofinformation.Usethefunctiontomakethreedictionariesrepresentingdifferentalbums.Printeachreturnvaluetoshowthatthedictionariesarestoringthealbuminformationcorrectly.

Addanoptionalparameterto make_album() thatallowsyoutostorethenubmeroftracksonanalbum.Ifthecallinglineincludesavalueforthenumberoftracks,addthatvaluetothealbum’sdictionary.Makeatleastonenewfunctioncallthatincludesthenubmeroftracksonanalbum.

Simpleversion:

defmake_album(artist,title):

"""Buildadictionarycontaininginformationaboutanalbum."""

album_dict={

'artist':

artist.title(),

'title':

title.title(),

}

returnalbum_dict

album=make_album('metallica','ridethelightning')

print(album)

album=make_album('beethoven','ninthsymphony')

print(album)

album=make_album('willienelson','red-headedstranger')

print(album)

Output:

{'title':

'RideTheLightning','artist':

'Metallica'}

{'title':

'NinthSymphony','artist':

'Beethoven'}

{'title':

'Red-HeadedStranger','artist':

'WillieNelson'}

Withtracks:

defmake_album(artist,title,tracks=0):

"""Buildadictionarycontaininginformationaboutanalbum."""

album_dict={

'artist':

artist.title(),

'title':

title.title(),

}

iftracks:

album_dict['tracks']=tracks

returnalbum_dict

album=make_album('metallica','ridethelightning')

print(album)

album=make_album('beethoven','ninthsymphony')

print(album)

album=make_album('willienelson','red-headedstranger')

print(album)

album=make_album('ironmaiden','pieceofmind',tracks=8)

print(album)

Output:

{'artist':

'Metallica','title':

'RideTheLightning'}

{'artist':

'Beethoven','title':

'NinthSymphony'}

{'artist':

'WillieNelson','title':

'Red-HeadedStranger'}

{'tracks':

8,'artist':

'IronMaiden','title':

'PieceOfMind'}

8-8:

UserAlbums

StartwithyourprogramfromExercise8-7.Writea while loopthatallowsuserstoenteranalbum’sartistandtitle.Onceyouhavethatinformation,call make_album() withtheuser’sinputandprintthedictionarythat’screated.Besuretoincludeaquitvalueinthe while loop.

defmake_album(artist,title,tracks=0):

"""Buildadictionarycontaininginformationaboutanalbum."""

album_dict={

'artist':

artist.title(),

'title':

title.title(),

}

iftracks:

album_dict['tracks']=tracks

returnalbum_dict

#Preparetheprompts.

title_prompt="\nWhatalbumareyouthinkingof?

"

artist_prompt="Who'stheartist?

"

#Lettheuserknowhowtoquit.

print("Enter'quit'atanytimetostop.")

whileTrue:

title=input(title_prompt)

iftitle=='quit':

break

artist=input(artist_prompt)

ifartist=='quit':

break

album=make_album(artist,title)

print(album)

print("\nThanksforresponding!

")

Output:

Enter'quit'atanytimetostop.

Whatalbumareyouthinkingof?

numberofthebeast

Who'stheartist?

ironmaiden

{'artist':

'IronMaiden','title':

'NumberOfTheBeast'}

Whatalbumareyouthinkingof?

touchofclass

Who'stheartist?

angelromero

{'artist':

'AngelRomero','title':

'TouchOfClass'}

Whatalbumareyouthinkingof?

rustinpeace

Who'stheartist?

megadeth

{'artist':

'Megadeth','title':

'RustInPeace'}

Whatalbumareyouthinkingof?

quit

Thanksforresponding!

8-9:

Magicians

Makealistofmagician’snames.Passthelisttoafunctioncalled show_magicians(),wichprintsthenameofeachmagicianinthelist.

defshow_magicians(magicians):

"""Printthenameofeachmagicianinthelist."""

formagicianinmagicians:

print(magician.title())

magicians=['harryhoudini','davidblaine','teller']

show_magicians(magicians)

Output:

HarryHoudini

DavidBlaine

Teller

8-10:

GreatMagicians

StartwithacopyofyourprogramfromExercise8-9.Writeafunctioncalled make_great() thatmodifiesthelistofmagiciansbyaddingthephrase theGreat toeachmagician’sname.Callshow_magicians() toseethatthelisthasactuallybeenmodified.

defshow_magicians(magicians):

"""Printthenameofeachmagicianinthelist."""

formagicianinmagicians:

print(magician)

defmake_great(magicians):

"""Add'theGreat!

'toeachmagician'sname."""

#Buildanewlisttoholdthegreatmusicians.

great_magicians=[]

#Makeeachmagiciangreat,andaddittogreat_magicians.

whilemagicians:

magician=magicians.pop()

great_magician=magician+'theGreat'

great_magicians.append(great_magician)

#Addthegreatmagiciansbackintomagicians.

forgreat_magicianingreat_magicians:

magicians.append(great_magician)

magicians=['HarryHoudini','DavidBlaine','Teller']

show_magicians(magicians)

print("\n")

make_great(magicians)

show_magicians(magicians)

Output:

HarryHoudini

DavidBlaine

Teller

TellertheGreat

DavidBlainetheGreat

HarryHoudinitheGreat

8-11:

UnchangedMagicians

StartwithyourworkfromExercise8-10.Callthefunction make_great() withacopyofthelistofmagicians’names.Becausetheoriginallistwillbeunchanged,returnthenewlistandstoreitinaseparatelist.Call show_magicians() witheachlisttoshowthatyouhaveonelistoftheoriginalnamesandonelistwith theGreat addedtoeachmagician’sname.

defshow_magicians(magicians):

"""Printthenameofeachmagicianinthelist."""

formagicianinmagicians:

print(magician)

defmake_great(magicians):

"""Add'theGreat!

'toeachmagician'sname."""

#Buildanewlisttoholdthegreatmusicians.

great_magicians=[]

#Makeeachmagiciangreat,andaddittogreat_magicians.

whilemagicians:

magician=magicians.pop()

great_magician=magician+'theGreat'

great_magicians.append(great_magician)

#Addthegreatmagiciansbackintomagicians.

forgreat_magicianingreat_magicians:

magicians.append(great_magician)

returnmagicians

magicians=['HarryHoudini'

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

当前位置:首页 > 高等教育 > 军事

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

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