栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

《python编程从入门到实践》第2版 第六章课后练习

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

《python编程从入门到实践》第2版 第六章课后练习

第六章

练习6-1: 人 使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name、last_name 、age 和city 。将存储在该字典中的每项信息都打印出来。

familiar_person = {
	'name': 'Sushan',
	'surname': 'Su',
	'age': 28,
	'city': 'chicago',
	'first_name': 'Su',
	'last_name': 'shan',
}
print(familiar_person['name'])
print(familiar_person['surname'])
print(familiar_person['age'])
print(familiar_person['city'])
print(familiar_person['first_name'])
print(familiar_person['last_name'])

输出:

Sushan
Su
28
chicago
Su
shan

练习6-2: 喜欢的数 使用一个字典来存储一些人喜欢的数。
请想出5个人的名字,并将这些名字用作字典中的键;找出每个人喜欢的一个数,并将这些数作为值存储在字典中。打印每个人的名字和喜欢的数。为了让这个程序更有趣,通过询问朋友确保数据是真实的。

favorite_numbers = {
	'TangSan': 666,
	'XiaoWu': 888,
	'DaiMuBai': 777,
	'ZhuQing': 333,
	'Pangzi': 555,
}

num = {favorite_numbers['TangSan']}
print(f"TangSan's favorite number is num.")

num = {favorite_numbers['XiaoWu']}
print(f"XiaoWu's favorite number is num.")

num = {favorite_numbers['DaiMuBai']}
print(f"DaiMuBai's favorite number is num.")

num = {favorite_numbers['ZhuQing']}
print(f"ZhuQing's favorite number is num.")

num = {favorite_numbers['Pangzi']}
print(f"Pangzi's favorite number is num.")

输出:

TangSan's favorite number is num.
XiaoWu's favorite number is num.
DaiMuBai's favorite number is num.
ZhuQing's favorite number is num.
Pangzi's favorite number is num.

练习6-3: 词汇表 Python字典可用于模拟现实生活中的字典。为避免混淆,我们将后者称为词汇表。

  • 想出你在前面学过的5个编程术语,将其用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
  • 以整洁的方式打印每个术语及其含义。为此,可先打印术语,在它后面加上一个冒号,再打印其含义;也可在一行打印术语,再使用换行符(n )插入一个空行,然后在下一行以缩进的方式打印其含义。
glossary = {
	'string': 'A series of characters',
	'comment': 'A note in a program that the Python interpreter ignores.',
	'list': 'A collection of items in a particular order.',
	'loop': 'Work through a collection of items. one at a time.',
	'dictionary': 'A collection of key-value pairs.',
}

word = 'string'
print(f"{word.title()}: {glossary[word]}")
word = 'comment'
print(f"{word.title()}: {glossary[word]}")
word = 'list'
print(f"{word.title()}: {glossary[word]}")
word = 'loop'
print(f"{word.title()}: {glossary[word]}")
word = 'dictionary'
print(f"{word.title()}: {glossary[word]}")

输出:

String: A series of characters
Comment: A note in a program that the Python interpreter ignores.
List: A collection of items in a particular order.
Loop: Work through a collection of items. one at a time.
Dictionary: A collection of key-value pairs.

练习 6-4: 词汇表 2 现在你知道了如何遍历字典,请整理你为完成练习 6-3 而编写的代码,将其中的一系列函数调用 print()替换为一个遍历字典中键和值的循环。确定该循环正确无误后,再在词汇表中添加 5 个 Python 术语。当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中。

glossary = {
	'string': 'A series of characters',
	'comment': 'A note in a program that the Python interpreter ignores.',
	'list': 'A collection of items in a particular order.',
	'loop': 'Work through a collection of items. one at a time.',
	'dictionary': 'A collection of key-value pairs.',
	'key': 'The first item in a key-value pair in a dictionary.',
	'value': 'An item associated with a key in a dictionary.',
	'conditional test': 'A comparison between two values.',
	'float': 'A numerical value with a decimal component.',
	'boolean expression': 'An expression that evaluates to True or False.',
}

for word,definition in glossary.items():
	print(f"{word.title()}: {definition}n")

输出:

String: A series of characters

Comment: A note in a program that the Python interpreter ignores.

List: A collection of items in a particular order.

Loop: Work through a collection of items. one at a time.

Dictionary: A collection of key-value pairs.

Key: The first item in a key-value pair in a dictionary.

Value: An item associated with a key in a dictionary.

Conditional Test: A comparison between two values.

Float: A numerical value with a decimal component.

Boolean Expression: An expression that evaluates to True or False.

练习 6-5: 河流 创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键值对可能是 ‘nile’: ‘egypt’ 。

  • 使用循环为每条河流打印一条消息,如 The Nile runs through Egypt。
  • 使用循环将该字典中每条河流的名字都打印出来。
  • 使用循环将该字典包含的每个国家的名字都打印出来。
rivers = {
 'nile': 'egypt',
 'mississippi': 'united states',
 'fraser': 'canada',
 'kuskokwim': 'alaska',
 'yangtze': 'china',
}

for river,country in rivers.items():
	print(f"The {river.title()} runs through {country.title()}.")

print("nThe following rivers are included in this data set:")
for river in rivers.keys():
	print(f"-{river}")

print("nThe following countries are included in this data set:")
for country in rivers.values():
	print(f"-{country}")

输出:

The Nile runs through Egypt.
The Mississippi runs through United States.
The Fraser runs through Canada.
The Kuskokwim runs through Alaska.
The Yangtze runs through China.

The following rivers are included in this data set:
-nile
-mississippi
-fraser
-kuskokwim
-yangtze

The following countries are included in this data set:
-egypt
-united states
-canada
-alaska
-china

练习 6-6: 调查 在 6.3.1 节编写的程序 favorite_languages.py 中执行以下操作。

  • 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
  • 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
}

for name,language in favorite_languages.items():
	print(f"{name.title()}'s favorite language is {language.title()}.")

print("n")

coders = ['phil', 'josh', 'david', 'becca', 'sarah', 'matt', 'danielle']
for coder in coders:
	if coder in favorite_languages.keys():
		print(f"Thank you for taking the poll,{coder.title()}!")
	else:
		print(f"{coder.title()}, what's your favorite programming language?")

输出:

Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.


Thank you for taking the poll,Phil!
Josh, what's your favorite programming language?
David, what's your favorite programming language?
Becca, what's your favorite programming language?
Thank you for taking the poll,Sarah!
Matt, what's your favorite programming language?
Danielle, what's your favorite programming language?

练习 6-7 人们 在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。

people = []

person = {
	'first_name': 'eric',
	'last_name': 'matthes',
	'age': 46,
	'city': 'sitka',
}
people.append(person)

person = {
	'first_name': 'lemmy',
	'last_name': 'matthes',
	'age': 2,
	'city': 'sitka',
}
people.append(person)

person = {
	'first_name': 'willie',
	'last_name': 'matthes',
	'age': 11,
	'city': 'sitka',
}
people.append(person)

for person in people:
	name = f"{person['first_name'].title()} {person['last_name'].title()}"
	age = person['age']
	city = person['city'].title()

    print(f"{name}, of {city}, is {age} years old.")

输出:

Eric Matthes, of Sitka, is 46 years old.
Lemmy Matthes, of Sitka, is 2 years old.
Willie Matthes, of Sitka, is 11 years old.

练习 6-8 宠物 创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为 pets 的列表中,再遍历该列表,并将有关每个宠物的所有信息都打印出来。

pets = []

pet = {
	'animal type': 'python',
	'name': 'john',
	'owener': 'guido',
	'weight': 43,
	'eats': 'bugs',
}
pets.append(pet)

pet = {
	'animal type': 'dog',
	'name': 'peso',
	'owener': 'eric',
	'weight': 37,
	'eats': 'shoes',
}
pets.append(pet)

for pet in pets:
	print(f"nHere's what I know about {pet['name'].title()}:")
	for key, value in pet.items():
		print(f"t{key}: {value}")

输出:

Here's what I know about John:
	animal type: python
	name: john
	owener: guido
	weight: 43
	eats: bugs

Here's what I know about Peso:
	animal type: dog
	name: peso
	owener: eric
	weight: 37
	eats: shoes

练习 6-9 喜欢的地方 创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的 1~3 个地方。为让这个练习更有趣些,让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。

favorite_places = {
	'eric': ['bear mountain', 'death valley', 'tierra del fuego'],
	'erin': ['hawaii', 'iceland'],
	'willie': ['mt. verstovia', 'the playground', 'new hampshire'],
}

for name, places in favorite_places.items():
	print(f"n{name.title()} likes the following places:")
	for place in places:
		print(f"- {place.title()}")

输出:

Eric likes the following places:
- Bear Mountain
- Death Valley
- Tierra Del Fuego

Erin likes the following places:
- Hawaii
- Iceland

Willie likes the following places:
- Mt. Verstovia
- The Playground
- New Hampshire

练习 6-10 喜欢的数 2 修改为完成练习 6-2 而编写的程序,让每个人都可以有多个喜欢的数,然后将每个人的名字及其喜欢的数打印出来。

favorite_numbers = {
	'mandy': [42, 17],
	'micah': [42, 39, 56],
	'gus': [7, 12],
 }

for name, numbers in favorite_numbers.items():
	print(f"n{name.title()} likes the following numbers:")
	for number in numbers:
		print(f" {number}")

输出:

Mandy likes the following numbers:
 42
 17

Micah likes the following numbers:
 42
 39
 56

Gus likes the following numbers:
 7
 12

练习 6-11 城市 创建一个名为 cities 的字典,在其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country 、population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。

cites = {
	'santiago': {
		'country': 'chile',
		'population': 6_310_000,
		'nearby mountains': 'andes',
	},
	'talkeetna': {
		'country': 'united states',
		'population': 876,
		'nearby mountains': 'alaska range',
	},
	'kathmandu': {
		'country': 'nepal',
		'population': 975_453,
		'nearby mountains': 'himilaya',
	}
}

for city, city_info in cites.items():
	country = city_info['country'].title()
	population = city_info['population']
	mountains = city_info['nearby mountains'].title()
	
	print(f"n{city.title()} is in {country}.")
	print(f"tIt has a population of about {population}.")
	print(f"tThe {mountains} mounats are nearby.")

输出:

Santiago is in Chile.
	It has a population of about 6310000.
	The Andes mounats are nearby.

Talkeetna is in United States.
	It has a population of about 876.
	The Alaska Range mounats are nearby.

Kathmandu is in Nepal.
	It has a population of about 975453.
	The Himilaya mounats are nearby.

6-12 扩展 本章的实例足够复杂,能以很多方式进行扩展。请对本章的一个示例进行扩展:添加键和值、调整程序要解决的问题或改进输出的格式。

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1037778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号